Merge branch 'main' into own-carrier-egress
This commit is contained in:
commit
296de1d946
232 changed files with 18447 additions and 2047 deletions
|
|
@ -3,31 +3,29 @@ const assert = require('node:assert/strict');
|
|||
const { load } = require('./harness');
|
||||
|
||||
const choose = (ev, v) => ev(`(()=>{const s=document.getElementById('homeSel');s.value=${JSON.stringify(v)};s.dispatchEvent(new Event('change',{bubbles:true}));})()`);
|
||||
const onTiles = ev => JSON.parse(ev("JSON.stringify([...document.querySelectorAll('.starts .start.on')].map(b=>b.dataset.city||'own'))"));
|
||||
|
||||
test('the title screen offers five homes and a sixth tile for any city, grouped by continent', () => {
|
||||
test('the title screen has one drawer for the home city: the five suggested first, then every city by continent', () => {
|
||||
const { ev, errors } = load();
|
||||
assert.equal(ev('S'), null, 'before any game exists');
|
||||
assert.equal(ev("document.querySelectorAll('.starts .start').length"), 6);
|
||||
const opts = JSON.parse(ev("JSON.stringify([...document.querySelectorAll('#homeSel option')].map(o=>o.value).filter(Boolean))"));
|
||||
const opts = JSON.parse(ev("JSON.stringify([...document.querySelectorAll('#homeSel option')].map(o=>o.value))"));
|
||||
assert.deepEqual(opts.slice(0, 5), ['fra', 'nyc', 'sin', 'sao', 'syd'], 'the suggested homes come first');
|
||||
assert.equal(new Set(opts).size, opts.length, 'no city twice');
|
||||
assert.ok(opts.length > 150, `lots of cities (${opts.length})`);
|
||||
assert.ok(opts.every(c => ev(`homeOk('${c}')`)), 'only cities that work as a home');
|
||||
assert.ok(!opts.some(c => ev(`!!CITY['${c}'].cn||!!CITY['${c}'].off`)), 'no hidden or Chinese cities');
|
||||
assert.ok(!opts.includes('stg'), 'no city without transit to buy');
|
||||
assert.ok(ev("document.querySelectorAll('#homeSel optgroup').length") >= 5, 'grouped by continent');
|
||||
assert.ok(ev("document.querySelectorAll('#homeSel optgroup').length") >= 6, 'suggested plus continents');
|
||||
assert.equal(ev("document.getElementById('homeSel').value"), 'fra');
|
||||
assert.equal(ev("document.querySelectorAll('.starts .start').length"), 0, 'no tiles any more');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('picking any city starts the network there, and the tiles follow the choice', () => {
|
||||
test('picking any city starts the network there, and the line under the drawer follows the choice', () => {
|
||||
const { ev, errors } = load();
|
||||
choose(ev, 'lis');
|
||||
assert.equal(ev('UI.startCity'), 'lis');
|
||||
assert.deepEqual(onTiles(ev), ['own'], 'the sixth tile lights up');
|
||||
assert.equal(ev("document.getElementById('homeWhat').textContent"), 'Lisbon · ' + ev("REG[CITY.lis.reg]"), 'and names the city in full');
|
||||
ev("document.querySelector('.start[data-city=nyc]').click()");
|
||||
assert.deepEqual(onTiles(ev), ['nyc'], 'a suggested tile takes over again');
|
||||
assert.equal(ev("document.getElementById('homeSel').value"), '', 'and the dropdown resets');
|
||||
assert.match(ev("document.getElementById('homeWhat').textContent"), /more cities/);
|
||||
choose(ev, 'nyc');
|
||||
assert.equal(ev("document.getElementById('homeWhat').textContent"), ev("tr('title.huge_eyeball_market_pricey')"), 'a suggested home says what it is like');
|
||||
choose(ev, 'akl');
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()");
|
||||
assert.equal(ev('S.home'), 'akl');
|
||||
|
|
@ -45,12 +43,15 @@ test('a home that cannot work is refused, and the game falls back to Frankfurt',
|
|||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the sixth tile works on a phone and in every language', () => {
|
||||
test('the title screen works on a phone in every language: language first, the name on top, compact presets', () => {
|
||||
for (const lang of ['en', 'it', 'pt', 'fr', 'es', 'de']) {
|
||||
const { ev, errors } = load(lang === 'en' ? {} : { lang });
|
||||
ev('window.innerWidth=360;showTitle()');
|
||||
assert.equal(ev("document.querySelector('label.start.own b').textContent"), ev("tr('title.anywhere_else')"), lang);
|
||||
if (lang !== 'en') assert.notEqual(ev("tr('title.anywhere_else')"), 'Anywhere else', `${lang}: translated`);
|
||||
const order = ev("(()=>{const c=document.getElementById('modalCard');const at=s=>[...c.querySelectorAll('*')].indexOf(c.querySelector(s));return [at('#langTitle'),at('.title-art'),at('#nmIn'),at('.doors'),at('#homeSel')].join(',')})()").split(',').map(Number);
|
||||
assert.ok(order.every((v, i) => v >= 0 && (i === 0 || v > order[i - 1])), `${lang}: language, title, name, doors, home (${order})`);
|
||||
assert.equal(ev("document.querySelectorAll('#modalCard .preset small,#modalCard .preset span').length"), 0, `${lang}: presets are just icon and name`);
|
||||
assert.ok(ev("document.getElementById('presetWhat').textContent.length") > 10, `${lang}: the chosen preset explained below`);
|
||||
if (lang !== 'en') assert.notEqual(ev("tr('title.suggested')"), 'Suggested', `${lang}: translated`);
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
182
tests/architect.test.js
Normal file
182
tests/architect.test.js
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
// Architect runs (prototype): one network built brief by brief, reviewed by a chaos monkey.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// Reference builds, brief by brief: [a, b, route] lays a tube (a diverse trench when the pair has one), ['@rm', city]
|
||||
// closes a POP. Each must pass every brief within budget and land at par.
|
||||
const REF = {
|
||||
euro: [[['ams', 'fra', 'land']], [['ams', 'par', 'land'], ['ams', 'lon', 'nshuttle']], [['par', 'fra', 'land']],
|
||||
[['ams', 'zrh', 'land'], ['par', 'zrh', 'land']], [['lon', 'par', 'pasdc'], ['ams', 'lon', 'concerto']], [['@rm', 'fra'], ['ams', 'dus', 'land'], ['ams', 'dus', 'land']]],
|
||||
usa: [[['ash', 'nyc', 'land']], [['ash', 'chi', 'land']], [['nyc', 'chi', 'land']], [], [['chi', 'dal', 'land'], ['dal', 'sjc', 'land']], [['chi', 'sjc', 'land']]],
|
||||
pacific: [[['tok', 'hkg', 'adc']], [['hkg', 'sin', 'land']], [['tok', 'hkg', 'apg']], [['hkg', 'sin', 'sjc2']], [['sin', 'syd', 'indigo']]],
|
||||
};
|
||||
const lay = (ev, a, b, via, div = 1) => ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:${div}});ACT.pzLink({tier:AR_TIER});closeModal()`);
|
||||
const review = (ev) => { ev('arShowStart();arShowSkip()'); return ev('S.ar.passed===pzSig()'); };
|
||||
|
||||
test('architect runs: every reference passes each brief, on plan and within budget', () => {
|
||||
const { ev, errors } = load();
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(AR_RUNS.map(r=>r.id))')).sort(), Object.keys(REF).sort());
|
||||
for (const [id, plan] of Object.entries(REF)) {
|
||||
ev(`ACT.pzArStart({id:'${id}'})`);
|
||||
assert.equal(ev('arOn()&&!!S.pops[S.ar.hq]'), true, `${id}: starts with a POP at HQ`);
|
||||
plan.forEach((steps, i) => {
|
||||
for (const s of steps) if (s[0] === '@rm') ev(`ACT.pzRmPop({city:'${s[1]}'})`); else lay(ev, ...s);
|
||||
assert.equal(review(ev), true, `${id} brief ${i + 1}: ${ev('arEval().why')} ${ev('JSON.stringify(UI.arFail)')}`);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify([UI.mk.mood,UI.mk.sprayAt])')), ['cheer', null], `${id}: a skipped review that passes still ends in a cheer`);
|
||||
if (i < plan.length - 1) { ev('ACT.pzArNext()'); assert.equal(ev('UI.mk'), null, `${id}: the monkey leaves with the next brief`); }
|
||||
});
|
||||
assert.equal(ev('arOver()'), 0, `${id}: never over a brief's tubes`);
|
||||
assert.equal(ev('arSpend()<=arRun().budget'), true, `${id}: within budget`);
|
||||
assert.ok(ev('arSpend()>arRun().budget*0.95'), `${id}: the budget sits just above the reference`);
|
||||
ev('ACT.pzArNext()');
|
||||
assert.equal(ev('JSON.parse(localStorage.getItem(AR_KEY)).runs[S.ar.id].st'), 3, `${id}: three stars stored`);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('architect runs: the chaos monkey finds a shared trench, edits clear the cut, old builds are paid for', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.pzArStart({id:'euro'})");
|
||||
assert.equal(ev("arHide('lis')&&arHide('bru')"), true, 'cities outside the run are hidden');
|
||||
assert.equal(ev("arHide('dus')"), true, 'a city a later brief adds stays hidden until then');
|
||||
// Later briefs stay a surprise: nothing on the map or a city card says where the run goes next.
|
||||
assert.equal(ev("typeof arTags"), 'undefined');
|
||||
ev("UI.sel={type:'city',id:'fra'};renderPanel()");
|
||||
assert.doesNotMatch(ev("document.getElementById('panelBody')?.textContent||''"), /brief \d|Coming up/i);
|
||||
ev('ACT.pzArAll()');
|
||||
assert.equal(ev("arHide('lis')"), false, 'and shown on request');
|
||||
ev('ACT.pzArAll()');
|
||||
lay(ev, 'ams', 'fra', 'land'); review(ev); ev('ACT.pzArNext()');
|
||||
lay(ev, 'ams', 'par', 'land'); lay(ev, 'ams', 'lon', 'nshuttle'); review(ev); ev('ACT.pzArNext()');
|
||||
lay(ev, 'ams', 'fra', 'land', 0); // the same trench: looks redundant, is not
|
||||
assert.equal(review(ev), false);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(UI.arFail.gold)')), ['fra']);
|
||||
assert.ok(ev('S.links.some(l=>l.cut)'), 'the failing cut stays on the map');
|
||||
ev('ACT.pzUndo()');
|
||||
assert.equal(ev('!UI.arFail&&!S.links.some(l=>l.cut)'), true, 'an edit clears it');
|
||||
const sunk = ev('S.ar.sunk');
|
||||
ev("ACT.pzRmLink({id:S.links.find(l=>l.br===0).id})");
|
||||
assert.ok(ev('S.ar.sunk') > sunk, 'removing an earlier brief\'s tube refunds nothing');
|
||||
ev('ACT.pzReset()');
|
||||
assert.equal(ev('S.ar.sunk'), sunk, 'reset goes back to the start of the brief');
|
||||
// Two diverse trenches would make both gold, but the plan has one tube: the ring is the answer.
|
||||
lay(ev, 'ams', 'fra', 'land'); lay(ev, 'ams', 'par', 'land');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(arTubes())')), { u: 2, max: 1, over: 1 });
|
||||
ev('ACT.pzReset()');
|
||||
lay(ev, 'par', 'fra', 'land');
|
||||
assert.equal(ev('arTubes().over'), 0);
|
||||
assert.equal(review(ev), true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('architect runs: a latency brief needs the fast path, and normal puzzles are untouched', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.pzArStart({id:'usa'})");
|
||||
lay(ev, 'ash', 'nyc', 'land'); review(ev); ev('ACT.pzArNext()');
|
||||
lay(ev, 'ash', 'chi', 'land'); review(ev); ev('ACT.pzArNext()');
|
||||
lay(ev, 'ash', 'nyc', 'land'); assert.equal(review(ev), true, 'a diverse trench makes New York gold'); ev('ACT.pzArNext()');
|
||||
assert.equal(ev('arEval().lat.ok'), false, 'via Ashburn is too slow');
|
||||
lay(ev, 'nyc', 'chi', 'land');
|
||||
assert.equal(ev('arEval().lat.ok&&arEval().ready'), true);
|
||||
ev("ACT.pzStart({id:'hello'})");
|
||||
assert.equal(ev('!S.ar&&pzKind("lon")==="goal"&&!arHide("par")'), true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('architect runs: Play on the title screen\'s puzzle list starts a run', () => {
|
||||
const { ev, errors } = load();
|
||||
ev('ACT.puzzleMenu()');
|
||||
assert.equal(ev('S'), null, 'no game loaded yet');
|
||||
ev("document.querySelector('#modal [data-act=pzArStart]').click()");
|
||||
assert.equal(ev('arOn()&&S.ar.id'), 'euro');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('architect runs: a ring goal needs one cycle through its cities', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.pzArStart({id:'euro'})");
|
||||
lay(ev, 'ams', 'fra', 'land'); review(ev); ev('ACT.pzArNext()');
|
||||
lay(ev, 'ams', 'par', 'land'); lay(ev, 'ams', 'lon', 'nshuttle'); review(ev); ev('ACT.pzArNext()');
|
||||
lay(ev, 'par', 'fra', 'land'); review(ev); ev('ACT.pzArNext()');
|
||||
lay(ev, 'ams', 'zrh', 'land'); lay(ev, 'par', 'zrh', 'land'); review(ev); ev('ACT.pzArNext()');
|
||||
assert.equal(ev("arRingOk(['ams','par','lon'])"), false, 'London hangs off Amsterdam: no ring');
|
||||
assert.match(ev('arEval().why'), /ring/i);
|
||||
lay(ev, 'lon', 'par', 'pasdc');
|
||||
assert.equal(ev("arRingOk(['ams','par','lon'])&&arEval().ready"), true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('architect runs: the detour needs room, and a roomy but pricey build misses the budget star', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.pzArStart({id:'euro'})");
|
||||
const head = [[['ams', 'fra', 'land']], [['ams', 'par', 'land'], ['ams', 'lon', 'nshuttle']], [['par', 'fra', 'land']]];
|
||||
const run = (plan) => plan.forEach((steps, i) => {
|
||||
for (const s of steps) if (s[0] === '@rm') ev(`ACT.pzRmPop({city:'${s[1]}'})`); else lay(ev, ...s);
|
||||
assert.equal(review(ev), true, `brief ${i + 1}: ${ev('arEval().why')} ${ev('JSON.stringify(UI.arFail)')}`);
|
||||
ev('ACT.pzArNext()');
|
||||
});
|
||||
run(head);
|
||||
// Zürich hung off Frankfurt: connected both ways, but a cut on Amsterdam-Frankfurt sends Frankfurt and Zürich through
|
||||
// Paris, and that tube is too thin for all three.
|
||||
lay(ev, 'fra', 'zrh', 'land'); lay(ev, 'par', 'zrh', 'land');
|
||||
assert.equal(review(ev), false);
|
||||
assert.ok(JSON.parse(ev('JSON.stringify(UI.arFail.short)')).length > 0, 'someone still connected runs short');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(UI.arFail.gold)')), [], 'nobody gold is cut off');
|
||||
ev('ACT.pzReset()');
|
||||
lay(ev, 'ams', 'zrh', 'land'); lay(ev, 'par', 'zrh', 'land');
|
||||
assert.equal(review(ev), true, 'Zürich straight to HQ spreads the detours');
|
||||
ev('ACT.pzArNext()');
|
||||
// Paris doubles: a second Amsterdam-Paris trench gives room, at a price.
|
||||
lay(ev, 'lon', 'par', 'pasdc'); lay(ev, 'ams', 'par', 'land');
|
||||
assert.equal(review(ev), true); ev('ACT.pzArNext()');
|
||||
ev("ACT.pzRmPop({city:'fra'})"); lay(ev, 'ams', 'dus', 'land'); lay(ev, 'dus', 'zrh', 'land');
|
||||
assert.equal(review(ev), true);
|
||||
assert.equal(ev('arOver()'), 0);
|
||||
assert.ok(ev('arSpend()') > ev('arRun().budget'));
|
||||
assert.equal(ev('arStars(arSpend())'), 2, 'on plan, over budget: two stars');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('architect runs: a bigger tube brings a bigger router, and changing an old tube is a new lease', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.pzArStart({id:'euro'})");
|
||||
lay(ev, 'ams', 'fra', 'land'); review(ev); ev('ACT.pzArNext()');
|
||||
assert.equal(ev("S.pops.ams.rgen||0"), 0, 'the free router takes 100G');
|
||||
const sunk = ev('S.ar.sunk');
|
||||
ev("ACT.pzTier({id:S.links[0].id,tier:2})");
|
||||
assert.ok(ev("RG[S.pops.ams.rgen].maxLT>=2&&RG[S.pops.fra.rgen].maxLT>=2"), '400G needs a bigger router at both ends');
|
||||
assert.ok(ev('S.ar.sunk') > sunk, 'the old 100G lease is paid for');
|
||||
ev('ACT.pzUndo()');
|
||||
assert.equal(ev("(S.pops.ams.rgen||0)===0&&S.ar.sunk===" + sunk), true, 'undo puts it all back');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('architect runs: the map tells two tubes in one trench from two separate paths', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.pzArStart({id:'euro'});ACT.pzArAll();S.cash=1e9");
|
||||
lay(ev, 'ams', 'fra', 'land', 1); lay(ev, 'ams', 'fra', 'land', 0);
|
||||
lay(ev, 'ams', 'par', 'land', 1); lay(ev, 'ams', 'par', 'land', 1);
|
||||
assert.equal(ev("arPaths(S.links.find(l=>l.b==='fra'||l.a==='fra'))"), 1, 'same trench: one path');
|
||||
assert.equal(ev("arPaths(S.links.find(l=>l.b==='par'||l.a==='par'))"), 2, 'diverse: two paths');
|
||||
ev("cam.x=CITY.ams.x;cam.y=CITY.ams.y;cam.z=2.4;drawFrame(performance.now())");
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(AR_PILLS.map(p=>p[2]).sort())")), ['2× one trench', '✓ 2 paths']);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#231 the puzzle list counts each section\'s own stars: runs above, packs next to the packs', () => {
|
||||
const { ev, errors } = load();
|
||||
// 2 stars on a pack puzzle, 2 on Euro Run, 3 on another run
|
||||
ev("localStorage.setItem(PZ_KEY,JSON.stringify({set:PZ_SET,noted:1,s:{[PZ[0].id]:{st:2}}}));localStorage.setItem(AR_KEY,JSON.stringify({runs:{[AR_RUNS[0].id]:{st:2},[AR_RUNS[1].id]:{st:3}}}))");
|
||||
ev('ACT.puzzleMenu()');
|
||||
const heads = JSON.parse(ev("JSON.stringify([...document.querySelectorAll('#modal h3.pzpack')].map(h=>h.textContent))"));
|
||||
assert.match(heads[0], new RegExp(`Architect runs ⭐ 5/${3 * ev('AR_RUNS.length')}`), heads[0]);
|
||||
// the packs' total sits right above the first pack, after the runs and the weekly puzzle, and says what it counts
|
||||
const order = ev(`(()=>{const m=document.querySelector('#modal'),box=m.querySelector('.pzprog'),run=m.querySelector('[data-act=pzArStart]'),pack=[...m.querySelectorAll('h3.pzpack')].find(h=>!h.textContent.includes('🏗️'));
|
||||
return [!!(run.compareDocumentPosition(box)&Node.DOCUMENT_POSITION_FOLLOWING),!!(box.compareDocumentPosition(pack)&Node.DOCUMENT_POSITION_FOLLOWING),box.textContent].join('|')})()`);
|
||||
const [afterRuns, beforePacks, box] = order.split('|');
|
||||
assert.equal(afterRuns, 'true', 'below the architect runs');
|
||||
assert.equal(beforePacks, 'true', 'above the first pack');
|
||||
assert.match(box, new RegExp(`Stars from the packs⭐ 2 / ${3 * ev('PZ.length')}`), box);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
220
tests/automation.test.js
Normal file
220
tests/automation.test.js
Normal file
|
|
@ -0,0 +1,220 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// #185's sales and repair engines now run as the NOC intern's standing orders, once per game day.
|
||||
function setup(ev) {
|
||||
ev("ACT.start({});S.cash=1e8;S.offers=[];S.biz=[];S.nextFail=S.nextEvent=1e6;for(const g of GOALS)S.done[g.id]=0;S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:1});S.lvl=2;S.ops.intern='kevin';S.ops.floor=0;S.rules=makeRules('freeze');compute()");
|
||||
}
|
||||
const orders = (ev, on) => ev(`for(const k of ${JSON.stringify(on)})S.ops.on[k]=true`);
|
||||
const shift = ev => ev('opsDay(S.day)');
|
||||
function offer(ev, id, extra = {}) {
|
||||
ev(`S.offers.push(${JSON.stringify({ id, city: 'fra', name: id, type: 'dia', bw: 1, rate: 600, reqs: [], exp: 30, ...extra })})`);
|
||||
}
|
||||
|
||||
test('the sales order signs ready offers once per shift, and pausing it stops it', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
setup(ev);
|
||||
offer(ev, 'first');
|
||||
shift(ev);
|
||||
assert.equal(ev('S.biz.length'), 0, 'off by default');
|
||||
orders(ev, ['sales']);
|
||||
shift(ev);
|
||||
assert.equal(ev('S.biz[0].id'), 'first');
|
||||
ev("ACT.opsToggle({k:'sales'})");
|
||||
offer(ev, 'off');
|
||||
ev('dayTick()');
|
||||
assert.equal(ev('S.biz.length'), 1, 'a paused order signs nothing');
|
||||
assert.ok(ev("S.offers.some(o=>o.id==='off')"));
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('the trial includes new bandwidth and later offers cannot overbook earlier accepted sales', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
setup(ev);
|
||||
offer(ev, 'one', { bw: 60 });
|
||||
offer(ev, 'two', { bw: 60 });
|
||||
const state = ev('JSON.stringify(S)');
|
||||
ev('window.beforeState=S;window.beforeResult=R;window.beforeHot=UI.hotMap');
|
||||
assert.equal(ev('!!autoOffer(S.offers[0])'), true);
|
||||
assert.equal(ev('JSON.stringify(S)'), state);
|
||||
assert.equal(ev('S===beforeState&&R===beforeResult&&UI.hotMap===beforeHot'), true);
|
||||
ev('S.ops.on.sales=true;opsDay(S.day)');
|
||||
assert.equal(ev('S.biz.length'), 1);
|
||||
assert.equal(ev('S.offers[0].id'), 'two');
|
||||
assert.ok(ev('bizSf(S.biz[0])') >= 0.95);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('the sales order checks actual circuits, latency and NNI capacity', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
setup(ev);
|
||||
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;compute()");
|
||||
offer(ev, 'circuit', { type: 'hft', city2: 'ams', bw: 10, latMax: 50, reqs: ['lat'] });
|
||||
assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'POPs alone are not a circuit');
|
||||
ev("S.links.push({id:'path',a:'fra',b:'ams',kind:'wave',tier:1,km:450,sub:false,cut:0,mo:1});compute()");
|
||||
assert.equal(ev('!!autoOffer(S.offers[0])'), true);
|
||||
ev('S.offers[0].latMax=0.1');
|
||||
assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'latency budget must pass');
|
||||
ev("S.offers=[];window.fabric=FABS.find(f=>f.cities.includes('fra')).id;ACT.buyNni({city:'fra',prov:fabric,tier:0})");
|
||||
const prov = ev('fabric');
|
||||
const bandwidth = ev('NNI[0].g * 0.75');
|
||||
offer(ev, 'fabric-one', { type: 'fabip', prov, bw: bandwidth, reqs: ['nni'] });
|
||||
offer(ev, 'fabric-two', { type: 'fabip', prov, bw: bandwidth, reqs: ['nni'] });
|
||||
// Transit has enough headroom, so the second rejection is the shared NNI port.
|
||||
ev("S.transit[0].tier=4;compute();S.ops.on.sales=true;opsDay(S.day)");
|
||||
assert.equal(ev('S.biz.length'), 1);
|
||||
assert.equal(ev('S.offers[0].id'), 'fabric-two');
|
||||
assert.ok(ev("nniUsed('fra',fabric)<=NNI[0].g"));
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('new circuits do not take service away from healthy signed customers', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
setup(ev);
|
||||
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;S.links.push({id:'path',a:'fra',b:'ams',kind:'wave',tier:1,km:450,sub:false,cut:0,mo:1});S.transit[0].city='ams';compute()");
|
||||
offer(ev, 'existing', { bw: 80 });
|
||||
ev("ACT.accept({id:'existing'})");
|
||||
offer(ev, 'new-circuit', { type: 'l2vpn', city2: 'ams', bw: 50 });
|
||||
assert.equal(ev('bizWhy(S.biz[0]).length'), 0);
|
||||
assert.equal(ev('!!autoOffer(S.offers[0])'), false);
|
||||
assert.ok(ev('bizSf(S.biz[0])') >= 0.95, 'failed preview leaves the old routing result intact');
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('fiber sales check live equipment and free spectrum, and repeated carrier orders still merge', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
setup(ev);
|
||||
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',own:true,sys:'lite',ch:Array(14).fill('zr4'),km:450,sub:false,ready:0,cut:0,mo:1}];S.biz=[{id:'old',name:'Same Carrier',type:'wwave',city:'fra',city2:'ams',link:'fiber',bw:1,rate:1000,slots:1,reqs:[],mood:100,since:0}];compute()");
|
||||
offer(ev, 'full', { type: 'wwave', city2: 'ams', link: 'fiber', slots: 2 });
|
||||
assert.equal(ev('!!autoOffer(S.offers[0])'), false);
|
||||
ev("S.offers[0].slots=1;S.offers[0].name='Same Carrier';S.links[0].eqDown=10;compute()");
|
||||
assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'a broken amplifier prevents a wave sale');
|
||||
ev('S.links[0].eqDown=0;compute();S.ops.on.sales=true;opsDay(S.day)');
|
||||
assert.equal(ev('S.biz.length'), 1);
|
||||
assert.equal(ev('S.biz[0].slots'), 2);
|
||||
assert.equal(ev('S.biz[0].rate'), 1600);
|
||||
assert.equal(ev('freeCh(S.links[0])'), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('capacity pair sales need completed infrastructure and reserve it for the accepted contract', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
setup(ev);
|
||||
offer(ev, 'pairs', { type: 'capfib', city2: 'ams', slots: 2, win: 90 });
|
||||
assert.equal(ev('!!autoOffer(S.offers[0])'), false);
|
||||
ev("ACT.buildPop({city:'ams'});S.links=[{id:'own',a:'fra',b:'ams',kind:'df',own:true,sys:'roadm',ch:[],km:450,sub:false,ready:0,cut:0,mo:1}];compute()");
|
||||
assert.equal(ev('!!autoOffer(S.offers[0])'), true);
|
||||
ev('S.ops.on.sales=true;opsDay(S.day)');
|
||||
assert.equal(ev('S.biz[0].link'), 'own');
|
||||
assert.equal(ev('capPend(S.biz[0])'), true, 'normal delivery handover still happens on a game day');
|
||||
offer(ev, 'second-pairs', { type: 'capfib', city2: 'ams', slots: 2, win: 90 });
|
||||
assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'the same trench cannot be promised twice');
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('future event demand is tested before signing, with booked events reserving headroom', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
setup(ev);
|
||||
offer(ev, 'event', { type: 'event', bw: 80, rate: 0, start: 10, dur: 3, fee: 5000, exp: 9 });
|
||||
assert.equal(ev('!!autoOffer(S.offers[0])'), true);
|
||||
ev('S.ops.on.sales=true;opsDay(S.day)');
|
||||
assert.equal(ev('S.biz[0].start'), 10, 'the trial does not move the actual event date');
|
||||
assert.equal(ev('R.cityDem.fra'), 0);
|
||||
offer(ev, 'too-large', { bw: 30 });
|
||||
assert.equal(ev('!!autoOffer(S.offers[0])'), false);
|
||||
ev('S.offers[0].bw=10');
|
||||
assert.equal(ev('!!autoOffer(S.offers[0])'), true);
|
||||
assert.equal(ev('S.biz[0].start'), 10);
|
||||
assert.equal(ev('R.cityDem.fra'), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('failed capacity trials restore game, routing and map state even when compute throws', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
setup(ev);
|
||||
offer(ev, 'ready');
|
||||
ev("window.beforeState=S;window.beforeResult=R;window.beforeHot=UI.hotMap;window.originalCompute=compute;window.compute=()=>{throw new Error('trial failed')}");
|
||||
assert.throws(() => ev('autoOffer(S.offers[0])'), /trial failed/);
|
||||
assert.equal(ev('S===beforeState&&R===beforeResult&&UI.hotMap===beforeHot'), true);
|
||||
ev('window.compute=originalCompute');
|
||||
assert.equal(ev('S.biz.length'), 0);
|
||||
assert.equal(ev('S.offers.length'), 1);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('the repair order rushes affordable repairs once, skips unaffordable and expired incidents, and obeys its pause', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
setup(ev);
|
||||
ev(`S.cash=10000;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,eqDown:10,chFail:{i:0,until:10},mo:1}];
|
||||
S.pops.fra.down=8;S.inc=[
|
||||
{id:'amp',type:'amp',ref:'fiber',until:10,cost:30000,msg:'Broken amp'},
|
||||
{id:'optic',type:'optic',ref:'fiber',until:10,cost:5000,msg:'Broken optic'},
|
||||
{id:'slow',type:'crash',ref:'fra',until:8,cost:2000,slow:true,msg:'Slow boot'},
|
||||
{id:'orphan',type:'amp',ref:'gone',until:10,cost:299,msg:'Removed equipment'},
|
||||
{id:'expired',type:'amp',ref:'fiber',until:0,cost:1000,msg:'Expired'},
|
||||
{id:'ddos',type:'ddos',ref:'fra',until:10,cost:1000,msg:'Attack'}];
|
||||
S.ops.on.repair=true;opsDay(S.day)`);
|
||||
assert.equal(ev('S.cash'), 3000);
|
||||
assert.equal(ev("S.inc.some(i=>i.id==='optic')"), false);
|
||||
assert.equal(ev('S.links[0].chFail'), null);
|
||||
assert.equal(ev("S.inc.find(i=>i.id==='slow').rushed"), true);
|
||||
assert.equal(ev("S.inc.find(i=>i.id==='slow').until"), 1);
|
||||
assert.equal(ev("S.inc.find(i=>i.id==='slow').cost"), 0);
|
||||
assert.equal(ev('S.pops.fra.down'), 1);
|
||||
ev('opsDay(S.day)');
|
||||
assert.equal(ev('S.cash'), 3000, 'no duplicate rush payment');
|
||||
ev('S.cash=40000;opsDay(S.day)');
|
||||
assert.equal(ev('S.cash'), 10000);
|
||||
assert.equal(ev('S.links[0].eqDown'), 0);
|
||||
assert.equal(ev("S.inc.some(i=>i.id==='amp')"), false);
|
||||
ev("ACT.opsToggle({k:'repair'});S.inc.push({id:'new',type:'amp',ref:'fiber',until:10,cost:1000,msg:'New failure'});opsDay(S.day)");
|
||||
assert.equal(ev('S.cash'), 10000);
|
||||
assert.equal(ev("S.inc.some(i=>i.id==='new')"), true);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('the sales order leaves unready and expired offers alone without failure notifications', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
setup(ev);
|
||||
offer(ev, 'generator', { reqs: ['gen'] });
|
||||
offer(ev, 'missing-pop', { city: 'ams' });
|
||||
offer(ev, 'scrub', { type: 'scrub' });
|
||||
offer(ev, 'expired', { exp: 0 });
|
||||
offer(ev, 'ipv6', { reqs: ['ipv6'] });
|
||||
const log = ev('S.log.length');
|
||||
ev('S.ops.on.sales=true;opsDay(S.day)');
|
||||
assert.equal(ev('S.biz.length'), 0);
|
||||
assert.equal(ev('S.offers.length'), 5);
|
||||
assert.equal(ev('S.log.length'), log, 'no failed manual-action toasts and no shift line when nothing got done');
|
||||
ev('S.pops.fra.gen=true;compute();opsDay(S.day)');
|
||||
assert.equal(ev('S.biz.length'), 1);
|
||||
assert.equal(ev('S.biz[0].id'), 'generator');
|
||||
// Manual acceptance keeps its existing sign-now, provision-later behavior.
|
||||
ev("ACT.accept({id:'scrub'})");
|
||||
assert.equal(ev("S.biz.some(b=>b.id==='scrub')"), true);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('the #185 toggles in old saves become the sales and repair orders, malformed ones stay off', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
setup(ev);
|
||||
ev("delete S.ops;S.autoSales=true;S.autoRepair=true;S=migrate(JSON.parse(JSON.stringify(S)))");
|
||||
assert.equal(ev('S.ops.on.sales&&S.ops.on.repair'), true);
|
||||
assert.equal(ev("'autoSales' in S||'autoRepair' in S"), false);
|
||||
assert.equal(ev('S.ops.intern'), null, 'no intern until you hire one, so nothing runs yet');
|
||||
ev("delete S.ops;S.autoSales='true';S.autoRepair=1;S=migrate(S)");
|
||||
assert.equal(ev('S.ops.on.sales||S.ops.on.repair'), false);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
257
tests/backbone-core.test.js
Normal file
257
tests/backbone-core.test.js
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const start = "ACT.start({});S.cash=1e9;S.lvl=13;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0";
|
||||
const g = n => `RG.findIndex(r=>r.n===${JSON.stringify(n)})`;
|
||||
|
||||
test('every router is classed by the highest backbone it runs', () => {
|
||||
const { ev, errors } = load();
|
||||
const want = {
|
||||
0: ['Rusty Router 9000', 'Edge Lord 400', 'Sonic the Whitebox 32'],
|
||||
1: ['Mikrowtik CCR', 'Mikrowtik CCR 3.2T'],
|
||||
2: ['Chonk 800', 'Brocadabra MLX-16', 'Extremely Networks SLX 9740'],
|
||||
3: ['Absolute Unit 1.6T', 'Arrrhipster 7280R', 'Arrrhipster 7800R', 'Arrrhipster 7800R5'],
|
||||
4: ['Absolute Unit 3.2T', 'Disco 8K', 'Disco 8K Ultra', 'Knockia 7750', 'Knockia 7950 XRS', 'Sonic the Whitebox 64', 'The Router at the End of the Universe'],
|
||||
};
|
||||
for (const [lv, names] of Object.entries(want)) for (const n of names) assert.equal(ev(`RG[${g(n)}].cr`), +lv, n);
|
||||
assert.equal(ev('RG.length'), Object.values(want).flat().length, 'every model is classed');
|
||||
assert.equal(ev("RG.filter(r=>r.v==='arrrhipster').some(r=>r.cr>=4)"), false, 'no Arrrhipster runs SRv6');
|
||||
assert.equal(ev("RG.filter(r=>r.v==='disco'||r.v==='knockia').every(r=>r.cr===4)"), true, 'every Disco and Knockia does');
|
||||
// Everything below its top, except the whitebox that does SRv6 natively and no MPLS at all.
|
||||
assert.equal(ev(`[0,1,2,3,4].map(L=>rgCore(${g('Disco 8K')},L)).join()`), 'true,true,true,true,true');
|
||||
assert.equal(ev(`[0,1,2,3,4].map(L=>rgCore(${g('Sonic the Whitebox 64')},L)).join()`), 'true,false,false,false,true');
|
||||
assert.equal(ev(`[0,1,2].map(L=>rgCore(${g('Mikrowtik CCR')},L)).join()`), 'true,true,false');
|
||||
// The two new ones go at the end, so saved POPs keep their models.
|
||||
assert.equal(ev(g('Brocadabra MLX-16')), ev('RG.length') - 2);
|
||||
assert.equal(ev("RG[RG_TOP].n"), 'The Router at the End of the Universe');
|
||||
assert.equal(ev("RG_ART.length"), ev("RG.length"), 'a picture for each');
|
||||
assert.equal(ev("mainRG(1)"), ev(g('Edge Lord 400')), 'the default upgrade path is unchanged');
|
||||
assert.equal(ev(`PZ_RG.includes(${g('Brocadabra MLX-16')})`), false, 'puzzles keep their router list');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a new network runs plain IGP: no Auto-TE until the backbone is upgraded, one step at a time', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
ev(start);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.core)')), { lv: 0, run: 0 });
|
||||
ev('ACT.buyTE()');
|
||||
assert.equal(ev('!!S.te'), false, 'no Auto-TE on plain IGP');
|
||||
ev("ACT.leftTab({t:'noc'})");
|
||||
assert.match(dom.window.document.body.textContent, /Backbone/);
|
||||
assert.match(dom.window.document.body.textContent, /Auto-TE needs an RSVP-TE/);
|
||||
const cash = ev('S.cash');
|
||||
ev('ACT.coreUp()');
|
||||
assert.equal(ev('S.core.lv'), 1);
|
||||
assert.equal(cash - ev('S.cash'), ev('CORE_COST[1]'));
|
||||
ev('ACT.buyTE()');
|
||||
assert.equal(ev('!!S.te'), false, 'LDP has no TE either');
|
||||
ev('ACT.coreUp()');
|
||||
assert.equal(ev('S.core.run'), 2);
|
||||
ev('ACT.buyTE()');
|
||||
assert.equal(ev('!!S.te'), true, 'RSVP-TE unlocks Auto-TE');
|
||||
// Customer levels gate each step.
|
||||
ev('S.lvl=3;ACT.coreUp()');
|
||||
assert.equal(ev('S.core.lv'), 2, 'SR-MPLS needs customer level 5');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('running a lower level is free, and Auto-TE and RouteScript pause below RSVP-TE', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start + ";ACT.coreUp();ACT.coreUp();ACT.coreUp();ACT.buyTE();S.te.script='spill at 80%'");
|
||||
assert.equal(ev('S.core.lv'), 3);
|
||||
assert.ok(ev('!!teRules()'), 'RouteScript runs on SR-MPLS');
|
||||
const cash = ev('S.cash');
|
||||
ev('ACT.coreSet({v:1})');
|
||||
assert.equal(ev('S.core.run'), 1);
|
||||
assert.equal(ev('S.cash'), cash, 'free');
|
||||
assert.equal(ev('teRules()'), null, 'paused on LDP');
|
||||
ev('compute()');
|
||||
assert.equal(ev('R.teMoved'), 0);
|
||||
ev('ACT.coreSet({v:3})');
|
||||
assert.ok(ev('!!teRules()'), 'back on, script and all');
|
||||
ev('ACT.coreSet({v:4})');
|
||||
assert.equal(ev('S.core.run'), 3, 'cannot run what was never bought');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the core costs router CPU, less the higher it goes; POPs whose router cannot run it stay outside', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start + `;ACT.buildPop({city:'ams'});S.pops.fra.rgen=${g('Disco 8K')}`);
|
||||
const cap = c => ev(`nodeCap('${c}')`);
|
||||
const base = cap('fra');
|
||||
const at = [];
|
||||
for (let L = 1; L <= 4; L++) { ev('ACT.coreUp()'); at.push(cap('fra') / base); }
|
||||
assert.deepEqual(at.map(x => +x.toFixed(2)), [0.9, 0.92, 0.95, 0.97], 'LDP costs the most CPU, SRv6 the least');
|
||||
assert.equal(ev("inCore('ams')"), false, 'a Rusty Router cannot run SRv6');
|
||||
assert.equal(cap('ams'), ev('RG[0].cap'), 'and pays no CPU for it');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(coreOut())')), ['ams']);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('label switching: traffic passing through a POP costs its router less from LDP up', () => {
|
||||
const pass = lv => {
|
||||
const { ev, errors } = load();
|
||||
ev(start + ";ACT.buildPop({city:'ams'});ACT.buildPop({city:'bru'});ACT.launchBB({city:'ams'});S.pops.ams.bb.d=150");
|
||||
ev(`for(const c in S.pops)S.pops[c].rgen=${g('Mikrowtik CCR')};S.pops.bru.rgen=${g('Chonk 800')};`);
|
||||
ev("const L=(a,b,t)=>{openLinkModal(a,b);ACT.buildLink({tier:t});closeModal();};L('ams','bru',1);L('bru','fra',1);ACT.buyTransit({city:'fra',net:'cog',tier:1})");
|
||||
for (let i = 0; i < lv; i++) ev('ACT.coreUp()');
|
||||
ev('compute()');
|
||||
assert.deepEqual(errors, []);
|
||||
return { load: ev("R.nodeLoad.bru||0"), served: ev('R.served') };
|
||||
};
|
||||
const ip = pass(0), ldp = pass(1);
|
||||
assert.ok(ip.served > 50 && Math.abs(ldp.served - ip.served) < 1, 'same traffic either way');
|
||||
assert.ok(ldp.load < ip.load * 0.7, `Brussels only passes it on: lighter with labels (${ldp.load.toFixed(1)} vs ${ip.load.toFixed(1)})`);
|
||||
});
|
||||
|
||||
test('interop failures: only with mixed vendors at the top of what some router can do', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start + `;ACT.buildPop({city:'ams'});S.pops.fra.rgen=${g('Disco 8K')};S.pops.ams.rgen=${g('Knockia 7750')};`);
|
||||
ev("const L=(a,b,t)=>{openLinkModal(a,b);ACT.buildLink({tier:t});closeModal();};L('fra','ams',1)");
|
||||
for (let i = 0; i < 4; i++) ev('ACT.coreUp()');
|
||||
assert.ok(ev('coreIopRisk()') > 0, 'Disco and Knockia at SRv6, the top for both');
|
||||
ev('ACT.coreSet({v:3})');
|
||||
assert.equal(ev('coreIopRisk()'), 0, 'one step below: they get along');
|
||||
ev('ACT.coreSet({v:4})');
|
||||
ev(`S.pops.ams.rgen=${g('Disco 8K Ultra')}`);
|
||||
assert.equal(ev('coreIopRisk()'), 0, 'one vendor never fights itself');
|
||||
ev(`S.pops.ams.rgen=${g('Knockia 7750')};ACT.coreSet({v:2})`);
|
||||
assert.equal(ev('coreIopRisk()'), 0, 'RSVP-TE is below both');
|
||||
ev(`S.pops.fra.rgen=${g('Chonk 800')}`);
|
||||
assert.ok(ev('coreIopRisk()') > 0, 'a Chonk 800 at RSVP-TE is at its top');
|
||||
assert.ok(ev('coreIopRisk()') < ev('CORE_IOP[4]'), 'and RSVP-TE squabbles less than SRv6');
|
||||
ev("fireFailure('interop')");
|
||||
const inc = "S.inc.find(i=>i.type==='interop')";
|
||||
assert.ok(ev(`!!${inc}`), 'an interop incident');
|
||||
assert.equal(ev(`linkDown(S.links.find(l=>l.id===${inc}.ref))`), true, 'the link between the vendors is down');
|
||||
assert.equal(ev("incTitle('interop')"), 'Vendor interop failure');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a new game never gets interop incidents or CPU costs: the classic game is unchanged', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start + `;ACT.buildPop({city:'ams'});S.pops.ams.rgen=${g('Knockia 7750')};S.pops.fra.rgen=${g('Disco 8K')}`);
|
||||
assert.equal(ev('coreIopRisk()'), 0);
|
||||
assert.equal(ev("nodeCap('ams')"), ev(`RG[${g('Knockia 7750')}].cap`));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('saves: an old save with Auto-TE keeps it on the old rules, scenarios ignore the core, garbage is repaired', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start + ";ACT.coreUp();ACT.coreUp();ACT.buyTE()");
|
||||
ev("const s=JSON.parse(JSON.stringify(S));delete s.core;window.__t=migrate(s)");
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(__t.core)')), { lv: 2, run: 2, legacy: true }, 'Auto-TE bought before backbones: legacy RSVP-TE');
|
||||
ev("S=__t;compute()");
|
||||
assert.equal(ev('coreOn()'), false, 'the old rules');
|
||||
assert.equal(ev('coreTE()'), true, 'Auto-TE keeps running');
|
||||
ev('ACT.coreSet({v:2})');
|
||||
assert.equal(ev('coreOn()'), true, 'changing the backbone switches to the new rules');
|
||||
ev("const s=JSON.parse(JSON.stringify(S));delete s.core;delete s.te;window.__t=migrate(s)");
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(__t.core)')), { lv: 0, run: 0 }, 'no Auto-TE: plain IGP');
|
||||
ev("const s=JSON.parse(JSON.stringify(S));s.core={lv:9,run:-3,legacy:'yes'};window.__t=migrate(s)");
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(__t.core)')), { lv: 4, run: 0 });
|
||||
ev("S.scn={id:'x',rules:{},days:9};S.core={lv:0,run:0}");
|
||||
assert.equal(ev('coreOn()'), false, 'scenarios set TE up themselves');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the backbone panel and the router panels, on a phone too', () => {
|
||||
for (const w of [1280, 360]) {
|
||||
const { ev, dom, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()");
|
||||
ev(`window.innerWidth=${w};` + start.replace('ACT.start({});', '') + `;ACT.buildPop({city:'ams'});S.pops.fra.rgen=${g('Disco 8K')};ACT.coreUp();ACT.coreUp();ACT.leftTab({t:'noc'});renderAll()`);
|
||||
const txt = dom.window.document.body.textContent;
|
||||
assert.match(txt, /RSVP-TE\/MPLS/, `${w}px`);
|
||||
assert.match(txt, /outside the backbone/, 'Amsterdam is left out');
|
||||
assert.match(txt, /Upgrade to SR-MPLS/);
|
||||
ev("UI.sel={type:'city',id:'fra'};UI.tab='links';UI.models=true;renderPanel()");
|
||||
const p = dom.window.document.getElementById('panelBody').textContent;
|
||||
assert.match(p, /Disco · backbone up to SRv6/);
|
||||
assert.match(p, /Brocadabra · backbone up to RSVP-TE\/MPLS/);
|
||||
assert.match(p, /Whitebox · backbone up to SRv6 · no MPLS, SRv6 only/);
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
});
|
||||
|
||||
test('an upgraded backbone brings its own customers: L3VPN from LDP, flex-algo from SR-MPLS, slices from SRv6', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start + ";for(const c of ['ams','lon','par'])ACT.buildPop({city:c});for(const c in S.pops)S.pops[c].rgen=" + g('Disco 8K'));
|
||||
const offered = () => ev("coreProducts(Object.keys(S.pops)).join()");
|
||||
assert.equal(offered(), '', 'plain IGP: none of them');
|
||||
ev('ACT.coreUp()');
|
||||
assert.equal(offered(), 'l3vpn,l3vpn');
|
||||
ev('ACT.coreUp();ACT.coreUp()');
|
||||
assert.equal(offered(), 'l3vpn,l3vpn,flex,flex');
|
||||
ev('ACT.coreUp()');
|
||||
assert.equal(offered(), 'l3vpn,l3vpn,flex,flex,slice,slice');
|
||||
ev('ACT.coreSet({v:0})');
|
||||
assert.equal(offered(), '', 'running plain IGP again: no new offers');
|
||||
// Each kind spawns a real offer that can be signed.
|
||||
ev('ACT.coreSet({v:4})');
|
||||
for (const t of ['l3vpn', 'flex', 'slice']) {
|
||||
ev(`S.offers=[];Math.random=(()=>{let s=7;return()=>(s=(s*9301+49297)%233280)/233280;})();for(let i=0;i<60&&!S.offers.some(o=>o.type==='${t}');i++){const p=coreProducts;coreProducts=()=>['${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}'];spawnOffer();coreProducts=p;}`);
|
||||
assert.ok(ev(`S.offers.some(o=>o.type==='${t}')`), `a ${t} offer`);
|
||||
assert.ok(ev(`S.offers.find(o=>o.type==='${t}').rate`) > 0, `${t} pays`);
|
||||
assert.equal(typeof ev(`bTerms(S.offers.find(o=>o.type==='${t}'))`), 'string');
|
||||
}
|
||||
// A legacy save or a scenario never sees them.
|
||||
ev("S.core.legacy=true");
|
||||
assert.equal(offered(), '');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('fast reroute: from RSVP-TE up, customers lose half as much happiness while a link is cut', () => {
|
||||
const hit = run => {
|
||||
const { ev, errors } = load();
|
||||
ev(start + `;ACT.buildPop({city:'ams'});S.pops.fra.rgen=S.pops.ams.rgen=${g('Disco 8K')};for(let i=0;i<${run};i++)ACT.coreUp();`);
|
||||
ev("const L=(a,b,t)=>{openLinkModal(a,b);ACT.buildLink({tier:t});closeModal();};L('fra','ams',1);S.links[0].ready=0");
|
||||
ev("S.biz.push({id:'b1',type:'dia',city:'ams',name:'X',bw:1,rate:600,mood:80,since:-99});S.links[0].cut=3;bizSf=()=>0.5;dayTick()");
|
||||
assert.deepEqual(errors, []);
|
||||
return 80 - ev("S.biz.find(b=>b.id==='b1').mood");
|
||||
};
|
||||
const plain = hit(0), frr = hit(2);
|
||||
assert.ok(plain > 0, 'a cut hurts');
|
||||
assert.ok(Math.abs(frr - plain / 2) < 0.01, `half as much with FRR (${plain} vs ${frr})`);
|
||||
assert.ok(Math.abs(hit(1) - plain) < 0.01, 'LDP has no fast reroute');
|
||||
});
|
||||
|
||||
test('an interop lab cuts interop incidents, is bought once, and survives a save', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start + `;ACT.buildPop({city:'ams'});S.pops.fra.rgen=${g('Disco 8K')};S.pops.ams.rgen=${g('Knockia 7750')};`);
|
||||
ev("const L=(a,b,t)=>{openLinkModal(a,b);ACT.buildLink({tier:t});closeModal();};L('fra','ams',1)");
|
||||
ev('ACT.coreLab()');
|
||||
assert.equal(ev('!!S.core.lab'), false, 'nothing to test on plain IGP');
|
||||
for (let i = 0; i < 4; i++) ev('ACT.coreUp()');
|
||||
const before = ev('coreIopRisk()'), cash = ev('S.cash');
|
||||
ev('ACT.coreLab()');
|
||||
assert.equal(ev('S.cash'), cash - ev('CORE_LAB'));
|
||||
assert.ok(Math.abs(ev('coreIopRisk()') - before * 0.4) < 1e-9, '60% fewer');
|
||||
ev('ACT.coreLab()');
|
||||
assert.equal(ev('S.cash'), cash - ev('CORE_LAB'), 'bought once');
|
||||
ev("S=sanitize(JSON.parse(JSON.stringify(S)))");
|
||||
assert.equal(ev('S.core.lab'), true);
|
||||
ev("S.core.lab='yes';S=sanitize(JSON.parse(JSON.stringify(S)))");
|
||||
assert.equal(ev('S.core.lab'), undefined, 'garbage is dropped');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('badges for the backbone: label switcher, bleeding edge, single-vendor shop, vendor zoo', () => {
|
||||
const { ev, errors } = load();
|
||||
const ok = id => ev(`BADGES.find(b=>b.id==='${id}').ok()`);
|
||||
ev(start + ";for(const c of ['ams','lon','par','bru','mad','mil','sto'])ACT.buildPop({city:c});for(const c in S.pops)S.pops[c].rgen=" + g('Disco 8K'));
|
||||
assert.equal(ev('Object.keys(S.pops).length'), 8);
|
||||
for (const id of ['label', 'bleed', 'mono', 'zoo']) assert.equal(ok(id), false, id);
|
||||
ev('ACT.coreUp()');
|
||||
assert.equal(ok('label'), true);
|
||||
ev('ACT.coreUp();ACT.coreUp()');
|
||||
assert.equal(ok('mono'), true, 'eight POPs of one vendor on SR-MPLS');
|
||||
ev('ACT.coreUp()');
|
||||
assert.equal(ok('bleed'), true);
|
||||
ev(`S.pops.ams.rgen=${g('Knockia 7750')};S.pops.lon.rgen=${g('Absolute Unit 3.2T')};S.pops.par.rgen=${g('Sonic the Whitebox 64')}`);
|
||||
assert.equal(ok('mono'), false);
|
||||
assert.equal(ok('zoo'), true, 'Disco, Knockia, Junipurr and Whitebox');
|
||||
ev('ACT.coreSet({v:0})');
|
||||
assert.equal(ok('zoo'), false, 'not on plain IGP');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
171
tests/badges-variants.test.js
Normal file
171
tests/badges-variants.test.js
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
// Badge variants by ruleset preset (2.0): On-call earns the standard badge, Change Freeze a frosted one and BGP at
|
||||
// 3 a.m. a fiery one; Sandbox and puzzles earn none. A harder preset upgrades a badge you already have.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// The preset is read from S.rules.preset until the ruleset feature lands with rulePreset().
|
||||
const start = (ev, preset) => {
|
||||
ev("localStorage.removeItem('sot-badges');ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
|
||||
if (preset) ev(`S.rules={preset:'${preset}'}`);
|
||||
ev("S.ach={};S.achP={};compute()");
|
||||
};
|
||||
const earnHello = (ev) => ev("S.pni.push({id:'x',net:'nfx',city:'fra',tier:0});compute();checkBadges()");
|
||||
const hof = (ev) => JSON.parse(ev("localStorage.getItem('sot-badges')||'{}'"));
|
||||
|
||||
test('every save without a preset plays On-call and earns the standard badge', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
assert.equal(ev('badgeVar()'), 'oncall');
|
||||
earnHello(ev);
|
||||
assert.ok(ev('S.ach.hello!==undefined'));
|
||||
assert.equal(ev('S.achP.hello'), 'oncall');
|
||||
assert.deepEqual(hof(ev).hello.vs && Object.keys(hof(ev).hello.vs), ['oncall']);
|
||||
assert.equal(hof(ev).hello.v, 'oncall');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('Change Freeze earns frosted badges and BGP at 3 a.m. fiery ones, shown in the toast and the list', () => {
|
||||
for (const [p, name, cls] of [['freeze', /Freeze-dried/, 'v-freeze'], ['bgp', /Forged at 3 a\.m\./, 'v-bgp']]) {
|
||||
const { ev, dom, errors } = load();
|
||||
start(ev, p);
|
||||
ev("window.__t=[];const _t=toast;toast=(h,...a)=>{window.__t.push(h);return _t(h,...a);}");
|
||||
earnHello(ev);
|
||||
assert.equal(ev('S.achP.hello'), p);
|
||||
assert.match(ev("window.__t.join(' ')"), name, `${p}: the toast names the variant`);
|
||||
ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderLeft()");
|
||||
const card = dom.window.document.querySelector(`#leftBody .bdg.on.${cls}`);
|
||||
assert.ok(card, `${p}: the badge list shows the variant`);
|
||||
assert.match(card.textContent, name);
|
||||
assert.equal(hof(ev).hello.v, p, 'remembered on this device');
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
});
|
||||
|
||||
test('Sandbox and puzzles earn no badges', () => {
|
||||
for (const p of ['sandbox', 'puzzle']) {
|
||||
const { ev, errors } = load();
|
||||
start(ev, p);
|
||||
earnHello(ev);
|
||||
assert.equal(ev('badgeVar()'), null);
|
||||
assert.equal(ev('Object.keys(S.ach).length'), 0, p);
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
ev("S.mode='sandbox'");
|
||||
earnHello(ev);
|
||||
assert.equal(ev('Object.keys(S.ach).length'), 0, 'the old sandbox mode too');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a harder preset upgrades a badge, an easier one never downgrades it', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev, 'freeze');
|
||||
earnHello(ev);
|
||||
const day = ev('S.ach.hello');
|
||||
ev("window.__t=[];const _t=toast;toast=(h,...a)=>{window.__t.push(h);return _t(h,...a);}");
|
||||
ev("S.rules.preset='oncall';checkBadges()");
|
||||
assert.equal(ev('S.achP.hello'), 'oncall', 'On-call beats Change Freeze');
|
||||
assert.match(ev("window.__t.join(' ')"), /Badge upgraded/);
|
||||
ev("S.day+=10;S.rules.preset='bgp';checkBadges()");
|
||||
assert.equal(ev('S.achP.hello'), 'bgp');
|
||||
assert.equal(ev('S.ach.hello'), day, 'the day it was first earned stays');
|
||||
ev("window.__t=[];S.rules.preset='freeze';checkBadges()");
|
||||
assert.equal(ev('S.achP.hello'), 'bgp', 'never downgraded');
|
||||
assert.equal(ev("window.__t.length"), 0, 'and no toast');
|
||||
const h = hof(ev).hello;
|
||||
assert.deepEqual(Object.keys(h.vs).sort(), ['bgp', 'freeze', 'oncall'], 'the collection holds every variant earned');
|
||||
assert.equal(h.v, 'bgp', 'the shelf shows the best one');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the collection counts badges per variant on this device, and fits a phone', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
ev('window.innerWidth=360');
|
||||
start(ev, 'bgp');
|
||||
earnHello(ev);
|
||||
ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderLeft()");
|
||||
const shelf = dom.window.document.querySelector('#leftBody .bshelf');
|
||||
assert.ok(shelf);
|
||||
const total = ev('BADGES.length');
|
||||
assert.match(shelf.textContent, new RegExp(`Forged at 3 a\\.m\\. 1/${total}`));
|
||||
assert.match(shelf.textContent, new RegExp(`Freeze-dried 0/${total}`));
|
||||
assert.ok(dom.window.document.querySelector('#leftBody .bsh.v-bgp.cur'), 'the variant this game earns is marked');
|
||||
assert.match(dom.window.document.getElementById('leftBody').textContent, /forged in fire/);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(badgeShelf(hof()))')), { freeze: 0, oncall: 0, bgp: 1 });
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('old saves and old halls of fame keep loading, as standard badges', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
// a 1.x save: S.ach holds days, no S.achP; a 1.x hall of fame: {d, n} per badge
|
||||
ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2025-01-02',n:'Old'},t1:{d:'2025-03-04',n:'Old'},junk:5}))");
|
||||
ev("const o=JSON.parse(JSON.stringify(S));o.ach={hello:12,t1:'400'};delete o.achP;S=migrate(o)");
|
||||
assert.equal(ev('S.achP.hello'), 'oncall');
|
||||
assert.equal(ev('S.ach.t1'), 400, 'days are numbers');
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(Object.keys(S.achP).sort())")), ['hello', 't1']);
|
||||
const h = JSON.parse(ev('JSON.stringify(hof())'));
|
||||
assert.equal(h.hello.v, 'oncall');
|
||||
assert.equal(h.hello.vs.oncall, '2025-01-02');
|
||||
assert.equal(h.junk, undefined, 'broken entries are dropped');
|
||||
// a hand-edited variant is not trusted
|
||||
ev("const o=JSON.parse(JSON.stringify(S));o.achP={hello:'lava',t1:'bgp'};S=migrate(o)");
|
||||
assert.equal(ev('S.achP.hello'), 'oncall');
|
||||
assert.equal(ev('S.achP.t1'), 'bgp');
|
||||
ev("localStorage.setItem('sot-badges','[1,2]')");
|
||||
assert.equal(ev('JSON.stringify(hof())'), '{}');
|
||||
ev("UI.left='goals';UI.leftOpen=true;renderLeft()");
|
||||
// new games start with an empty variant map
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()");
|
||||
assert.equal(ev('JSON.stringify(S.achP)'), '{}');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the share card rings the variant badges', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev, 'bgp');
|
||||
earnHello(ev);
|
||||
// count the strokes the card draws with a variant badge and with the same badge in its standard look
|
||||
const calls = () => ev("(()=>{const cv=shareCanvas();return cv.getContext('2d').calls.n;})()");
|
||||
const fiery = calls();
|
||||
ev("S.achP.hello='oncall'");
|
||||
const plain = calls();
|
||||
assert.ok(fiery > plain, `the ring and the tally are drawn (${fiery} > ${plain} calls)`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a variant named after an Object prototype key is not a variant', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
for (const k of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) {
|
||||
ev(`const o=JSON.parse(JSON.stringify(S));o.ach={hello:3};o.achP={hello:${JSON.stringify(k)}};S=migrate(o)`);
|
||||
assert.equal(ev('S.achP.hello'), 'oncall', k);
|
||||
assert.equal(ev(`bvar(${JSON.stringify(k)}).k`), 'oncall', `bvar(${k})`);
|
||||
ev(`S.rules={preset:${JSON.stringify(k)}}`);
|
||||
assert.equal(ev('badgeVar()'), 'oncall', `badgeVar() under preset ${k}`);
|
||||
}
|
||||
ev("S.rules={preset:'oncall'};S.achP.hello='constructor';shareCanvas()");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('"Badge upgraded" means the collection on this device got a better variant', () => {
|
||||
const { ev, errors } = load();
|
||||
const spy = () => ev("window.__t=[];if(!window.__sp){window.__sp=1;const _t=toast;toast=(h,...a)=>{window.__t.push(h);return _t(h,...a);};}");
|
||||
// a new game, but this device already holds the frosted badge: the standard one upgrades it
|
||||
start(ev, 'oncall');
|
||||
ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2026-01-01',n:'Old',vs:{freeze:'2026-01-01'}}}))");
|
||||
spy(); earnHello(ev);
|
||||
assert.match(ev("window.__t.join(' ')"), /Badge upgraded/);
|
||||
assert.equal(hof(ev).hello.v, 'oncall');
|
||||
// another new game, the device already holds the fiery one: earning the frosted one is a plain unlock
|
||||
start(ev, 'freeze');
|
||||
ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2026-01-01',n:'Old',vs:{bgp:'2026-01-01'}}}))");
|
||||
spy(); earnHello(ev);
|
||||
const t = ev("window.__t.join(' ')");
|
||||
assert.match(t, /Badge unlocked/);
|
||||
assert.doesNotMatch(t, /Badge upgraded/);
|
||||
assert.equal(hof(ev).hello.v, 'bgp', 'the best variant stays on the shelf');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
120
tests/chaos-monkey.test.js
Normal file
120
tests/chaos-monkey.test.js
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// A small network on a fixed seed: Frankfurt, Amsterdam, London and Paris in a ring, with a spur out to Zurich.
|
||||
function net(preset) {
|
||||
const { ev, errors, dom } = load();
|
||||
ev(`beginGame('Monkey Testers','fra',${JSON.stringify({ mode: 'normal', preset })});if(UI.pendGame)ACT.pitchSkip()`);
|
||||
ev("S.cash=1e9;S.lvl=4;for(const c of ['ams','lon','par','zrh'])ACT.buildPop({city:c})");
|
||||
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1})");
|
||||
ev("for(const [a,b] of [['fra','ams'],['ams','lon'],['lon','par'],['par','fra'],['fra','zrh']]){UI.pending={a,b};ACT.buildLink({tier:1});}closeModal()");
|
||||
ev('for(let i=0;i<60;i++)dayTick();S.inc=[];for(const l of S.links)l.cut=0;compute()');
|
||||
return { ev, errors, dom };
|
||||
}
|
||||
const link = (ev, a, b) => `S.links.find(l=>(l.a==='${a}'&&l.b==='${b}')||(l.a==='${b}'&&l.b==='${a}'))`;
|
||||
|
||||
test('the chaos monkey visits On-call and BGP at 3 a.m., never Change Freeze or Sandbox', () => {
|
||||
for (const [preset, ok] of [['oncall', true], ['bgp', true], ['freeze', false]]) {
|
||||
const { ev, errors } = net(preset);
|
||||
assert.equal(ev('mkElig()'), ok, preset);
|
||||
ev('S.monkey.next=S.day;dayTick()');
|
||||
assert.equal(ev('!!S.monkey.on'), ok, preset);
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
const { ev } = net('oncall');
|
||||
ev("S.mode='sandbox'");
|
||||
assert.equal(ev('mkElig()'), false);
|
||||
ev("S.mode='normal';S.monkey.next=S.day;dayTick();S.scn={rules:{}}");
|
||||
assert.equal(ev('mkOn()'), false, 'never in a scenario');
|
||||
});
|
||||
|
||||
test('a visit lasts 120 to 240 days, snips every couple of weeks and pauses the usual failures', () => {
|
||||
const { ev, errors } = net('oncall');
|
||||
ev('S.monkey.next=S.day;dayTick()');
|
||||
const len = ev('S.monkey.until-S.monkey.start');
|
||||
assert.ok(len >= 120 && len <= 240, `visit of ${len} days`);
|
||||
ev('S.nextFail=S.day');
|
||||
const nf = ev('S.nextFail');
|
||||
ev('for(let i=0;i<60;i++)dayTick()');
|
||||
assert.ok(ev('S.monkey.n') >= 2, 'it snipped');
|
||||
assert.equal(ev('S.nextFail'), nf, 'no ordinary failure fired while it was here');
|
||||
assert.ok(ev("S.inc.some(i=>i.type==='cut')||S.stats.survived>0"));
|
||||
// It leaves on time, and the ordinary failures wait a little before they start again.
|
||||
ev('for(let i=0;i<200&&S.monkey.on;i++)dayTick()');
|
||||
assert.equal(ev('S.monkey.on'), 0);
|
||||
assert.ok(ev('S.monkey.next>S.day+200'));
|
||||
assert.ok(ev('S.nextFail>=S.day'));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('weak spots are tubes with no other way round', () => {
|
||||
const { ev } = net('oncall');
|
||||
assert.equal(ev(`mkWeak(${link(ev, 'fra', 'zrh')})`), true);
|
||||
assert.equal(ev(`mkWeak(${link(ev, 'fra', 'ams')})`), false);
|
||||
});
|
||||
|
||||
test('outlasting it unnoticed pays a bonus and earns the badge; going home hurt pays nothing', () => {
|
||||
const { ev, errors } = net('oncall');
|
||||
ev('S.monkey.next=S.day;dayTick();S.monkey.n=4;S.monkey.hurt=0;S.monkey.until=S.day+1');
|
||||
const cash = ev('S.cash'), bonus = ev('mkBonus()');
|
||||
ev('dayTick();checkBadges()');
|
||||
assert.equal(ev('S.monkey.on'), 0);
|
||||
assert.equal(ev('S.stats.mkSurv'), 1);
|
||||
assert.ok(ev('S.cash') >= cash + bonus - 1e6, 'bonus paid');
|
||||
assert.ok(ev("S.ach.monkey!==undefined"));
|
||||
ev('S.monkey.next=S.day;dayTick();S.monkey.n=4;S.monkey.hurt=2;S.monkey.until=S.day+1;dayTick()');
|
||||
assert.equal(ev('S.stats.mkSurv'), 1, 'no bonus when customers felt it');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a banana sends it home early, for a price', () => {
|
||||
const { ev, errors, dom } = net('bgp');
|
||||
ev("S.monkey.next=S.day;dayTick();UI.left='noc';renderLeft()");
|
||||
assert.ok(dom.window.document.querySelector('[data-act=mkBanana]'), 'the NOC card offers a banana');
|
||||
const cash = ev('S.cash'), cost = ev('mkBananaCost()');
|
||||
ev('ACT.mkBanana({})');
|
||||
assert.equal(ev('S.monkey.on'), 0);
|
||||
assert.equal(ev('S.cash'), cash - cost);
|
||||
assert.equal(ev('S.stats.mkSurv||0'), 0);
|
||||
ev('S.cash=0;S.monkey.next=S.day;dayTick();ACT.mkBanana({})');
|
||||
assert.equal(ev('S.monkey.on'), 1, 'no banana without the cash');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('saves keep the monkey; old and broken saves are repaired', () => {
|
||||
const { ev, errors } = net('oncall');
|
||||
ev('S.monkey.next=S.day;dayTick();const t=JSON.stringify(packSave(S));S=migrate(JSON.parse(t))');
|
||||
assert.equal(ev('S.monkey.on'), 1);
|
||||
assert.ok(ev('S.monkey.until>S.day'));
|
||||
ev("const o=JSON.parse(JSON.stringify(packSave(S)));delete o.monkey;S=migrate(o)");
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.monkey)')), { next: null, on: 0 });
|
||||
ev("const o=JSON.parse(JSON.stringify(packSave(S)));o.monkey={on:1,until:'soon',n:-3,hurt:99,c:'<b>'};S=migrate(o)");
|
||||
assert.equal(ev('S.monkey.n'), 0);
|
||||
assert.equal(ev('S.monkey.hurt'), 0);
|
||||
assert.equal(ev('S.monkey.c'), ev('S.home'));
|
||||
assert.ok(ev('S.monkey.until>=S.monkey.start'));
|
||||
ev('for(let i=0;i<5;i++)dayTick()');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('"Met the Chaos Monkey" comes from a visit, not from an ordinary fiber cut', () => {
|
||||
const { ev, errors } = net('oncall');
|
||||
ev("fireFailure('cut');checkBadges()");
|
||||
assert.equal(ev('S.ach.backhoe===undefined'), true, 'a cut alone is not the monkey');
|
||||
ev('S.monkey.next=S.day;dayTick();checkBadges()');
|
||||
assert.notEqual(ev('S.ach.backhoe'), undefined);
|
||||
assert.equal(ev("BADGES.find(b=>b.id==='backhoe').t"), 'Met the Chaos Monkey');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#226 the monkey\'s notice in the NOC has no Open button that would open the NOC again', () => {
|
||||
const { ev, errors } = net('oncall');
|
||||
ev('mkArrive(S.day);ACT.leftTab({t:"noc"})');
|
||||
const row = ev(`(()=>{const e=S.log.find(x=>x.o&&x.o.a==='tab'&&x.o.v==='noc');if(!e)return 'none';const r=[...document.querySelectorAll('#left .row.note')].find(n=>n.textContent.includes(e.t.slice(0,20)));return r?(r.querySelector('[data-act=logOpen]')?'button':'no button'):'not shown'})()`);
|
||||
assert.equal(row, 'no button');
|
||||
// a notice that opens something else keeps its button
|
||||
ev("toast('A test notice','',[],{a:'bank'});ACT.leftTab({t:'noc'})");
|
||||
assert.equal(ev(`!![...document.querySelectorAll('#left .row.note')].find(n=>n.textContent.includes('A test notice')).querySelector('[data-act=logOpen]')`), true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
81
tests/city-size.test.js
Normal file
81
tests/city-size.test.js
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// A game with three POPs around Europe, and a hook that keeps the cities cityRoom() saw on the last frame.
|
||||
function game(t) {
|
||||
const h = load();
|
||||
t.after(() => h.dom.window.close());
|
||||
h.ev("ACT.start({});S.lvl=6;S.cash=1e9;for(const c of ['ams','lon','par'])ACT.buildPop({city:c});UI.speed=0;compute()");
|
||||
h.ev("window.__v=null;const o=cityRoom;cityRoom=(v,s)=>{o(v,s);window.__v=v;}");
|
||||
return h;
|
||||
}
|
||||
// Draw one frame at a zoom and return what each visible city got: tier, room, dot or not, label or not.
|
||||
const frame = (ev, z, x = 1040, y = 300) => {
|
||||
ev(`window.__v=null;cam.x=${x};cam.y=${y};cam.z=${z};draw(0)`);
|
||||
return JSON.parse(ev("JSON.stringify((window.__v||[]).map(v=>({id:v.C.id,P:v.C.P,t:cTier(v.C.id),sx:v.sx,sy:v.sy,r:v.r,dem:v.dem,pr:v.pr,ly:v.ly})))"));
|
||||
};
|
||||
const near = (a, b) => Math.hypot(a.sx - b.sx, a.sy - b.sy) < a.r + b.r - 1e-6;
|
||||
|
||||
test('five city sizes from eyeballs: megacities are rare, outposts are huts', t => {
|
||||
const { ev, errors } = game(t);
|
||||
assert.equal(ev("cTier('sha')"), 4, 'Shanghai');
|
||||
assert.equal(ev("cTier('nyc')"), 4, 'New York');
|
||||
assert.equal(ev("cTier('dks')"), 0, 'Dikson');
|
||||
const n = JSON.parse(ev("JSON.stringify([0,1,2,3,4].map(t=>CITIES.filter(C=>cTier(C.id)===t).length))"));
|
||||
assert.ok(n.every(x => x > 0), `every size is used: ${n}`);
|
||||
assert.ok(n[4] <= 20, `megacities stay rare: ${n[4]}`);
|
||||
// bigger cities draw bigger, near and far
|
||||
assert.equal(ev("[1,2,3,4].every(t=>SKY_H[t]>SKY_H[t-1]&&SKY_W[t]>SKY_W[t-1]&&FAR_R[t]>FAR_R[t-1])"), true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('crowded small cities give way to bigger ones as dots; your POPs and the selected city never do', t => {
|
||||
const { ev, errors } = game(t);
|
||||
ev("UI.sel={type:'city',id:'bru'}");
|
||||
const v = frame(ev, 1.05);
|
||||
assert.ok(v.length > 50 && v.some(x => x.dem), 'a crowded view has dots');
|
||||
for (const x of v.filter(x => x.pr <= 2)) assert.equal(x.dem, false, `${x.id} keeps its icon`);
|
||||
assert.equal(v.find(x => x.id === 'bru').dem, false, 'the selected city');
|
||||
for (const id of ['ams', 'lon', 'par']) assert.equal(v.find(x => x.id === id).dem, false, `POP ${id}`);
|
||||
const full = v.filter(x => !x.dem);
|
||||
// two ordinary cities with full icons never sit on each other
|
||||
for (const a of full) for (const b of full) if (a !== b && a.pr === 3 && b.pr === 3) assert.ok(!near(a, b), `${a.id} and ${b.id} overlap`);
|
||||
// a city only gives way to one that is more important or at least as big
|
||||
for (const d of v.filter(x => x.dem)) assert.ok(full.some(b => near(d, b) && (b.pr < d.pr || b.P >= d.P)), `${d.id} gave way to nothing bigger`);
|
||||
// and a dot gets no label
|
||||
for (const d of v.filter(x => x.dem)) assert.equal(d.ly, null, `${d.id} has no label`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('zooming in gives every city its skyline back; zoomed out the map is dots sized by eyeballs', t => {
|
||||
const { ev, errors } = game(t);
|
||||
const dots = z => frame(ev, z).filter(x => x.dem).length;
|
||||
const a = dots(1.05), b = dots(1.7), c = dots(3.2);
|
||||
assert.ok(a > b && b > c, `fewer dots as you zoom in: ${a}, ${b}, ${c}`);
|
||||
assert.equal(c, 0, 'close in, every city in view has its skyline');
|
||||
// far view: no room to share, every city is a dot drawn by size (cityRoom is not needed)
|
||||
assert.equal(frame(ev, 0.5).length, 0);
|
||||
assert.equal(ev('CM.far'), true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a city shown as a dot is still there to tap', t => {
|
||||
const { ev, errors } = game(t);
|
||||
const v = frame(ev, 1.05);
|
||||
const lone = v.filter(x => x.dem).find(d => v.every(o => o === d || Math.hypot(o.sx - d.sx, o.sy - d.sy) > 24));
|
||||
assert.ok(lone, 'a dot with nothing right next to it');
|
||||
assert.equal(ev(`(pickCity(${lone.sx},${lone.sy + 2})||{}).id`), lone.id);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('phones draw cities a little smaller, so more of them keep their skyline', t => {
|
||||
const { ev, errors } = game(t);
|
||||
const desk = frame(ev, 1.05).filter(x => x.dem).length;
|
||||
ev("Object.defineProperty(window,'innerWidth',{value:390,configurable:true})");
|
||||
assert.equal(ev('cityScale(1)'), 0.82);
|
||||
const v = frame(ev, 1.3);
|
||||
assert.ok(v.length > 0 && v.filter(x => !x.dem).every(x => x.r <= 40), 'small enough for a narrow screen');
|
||||
assert.ok(desk > 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
42
tests/compute-idempotent.test.js
Normal file
42
tests/compute-idempotent.test.js
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
const big = (t) => { const h = load({ seed: 777 }); t.after(() => h.dom.window.close());
|
||||
h.ev(`S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();`); return h; };
|
||||
// R as JSON; DDoS reports hold the live attack, whose `worst` dayTick updates, so it is named by id.
|
||||
const rj = (ev) => ev("JSON.stringify(R,(k,v)=>k==='attack'||k==='parent'?(v&&v.id):v)");
|
||||
|
||||
test('95th percentile: a recompute later in the day bills the same 30 days as the day tick did', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'lvl',tier:1});closeModal()");
|
||||
// Thirty days on file, two of them huge: counting today twice (and dropping the oldest day left) would lose one.
|
||||
ev("S.offers=[];const t=S.transit[0];t.hist=Array.from({length:30},(_,i)=>i===1||i===3?5000:1);S.nextFail=S.nextEvent=S.day+99;dayTick()");
|
||||
const tick = ev('R.p95[S.transit[0].id]'), cost = ev('R.cost.transit');
|
||||
assert.equal(tick, 5000, 'the tick bills the 29 days before today and today');
|
||||
ev('compute()');
|
||||
assert.equal(ev('R.p95[S.transit[0].id]'), tick);
|
||||
assert.equal(ev('R.cost.transit'), cost);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('compute() is a pure function of the game: a second call right after a day changes nothing', (t) => {
|
||||
const { ev, errors } = big(t);
|
||||
for (let d = 0; d < 4; d++) {
|
||||
ev('S.nextFail=S.day+99;S.nextEvent=S.day+99;dayTick();compute()');
|
||||
const a = rj(ev); ev('compute()');
|
||||
assert.equal(rj(ev), a, `day ${d}`);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('scenic circuits keep the last path unless a new one is clearly better, so two calls converge', (t) => {
|
||||
const { ev, errors } = big(t);
|
||||
ev("for(const b of S.biz)if(BIZ_T[b.type].l2)b.route='scenic';R=emptyR();compute()");
|
||||
ev('compute()'); const b = rj(ev);
|
||||
ev('compute()'); assert.equal(rj(ev), b);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
155
tests/ddos-floods.test.js
Normal file
155
tests/ddos-floods.test.js
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
// Where a flood goes and who pays for it: junk enters at its ingress ports and rides your backbone to the victim.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// Frankfurt has the eyeballs and no transit; all transit is in Amsterdam, 100G of wave away.
|
||||
const remoteTransit = (ev, flip) => {
|
||||
ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.buildPop({city:'ams'});ACT.launchBB({city:'fra'});S.links.push({id:'L',a:'fra',b:'ams',kind:'wave',tier:1,km:400,mo:1,cut:0});ACT.buyTransit({city:'ams',net:NETS.find(n=>sellsAt(n,'ams')).id,tier:1})");
|
||||
if (flip) ev("const p=S.pops;S.pops={ams:p.ams,fra:p.fra}");
|
||||
ev("compute()");
|
||||
};
|
||||
|
||||
test('a flood loads the backbone and the victim as on main, whatever order the POPs were built in', () => {
|
||||
const out = [];
|
||||
for (const flip of [false, true]) {
|
||||
const { ev, errors } = load({ seed: 5 });
|
||||
remoteTransit(ev, flip);
|
||||
assert.ok(ev("sfOf(R,'fra')") > 0.95, 'fine before the attack');
|
||||
ev("S.day=60;ddosAttack();Object.assign(S.ev.ddos,{city:'fra',vec:'http',gbps:300});compute()");
|
||||
assert.equal(ev('S.ev.ddos.entries'), undefined, 'no per-port shares');
|
||||
assert.equal(ev('R.load.L'), 100, 'the junk fills the wave between the transit and the victim');
|
||||
assert.ok(ev('R.nodeLoad.fra') >= 100, "and the victim's router");
|
||||
assert.ok(ev("sfOf(R,'fra')") < 0.05, 'the victim goes dark');
|
||||
assert.equal(ev("sfOf(R,'ams')"), 1);
|
||||
out.push(ev("JSON.stringify([R.load.L,Object.values(R.useT)[0],sfOf(R,'fra'),R.ddos.length])"));
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
assert.equal(out[0], out[1], 'POP build order does not change the outcome');
|
||||
});
|
||||
|
||||
test('the same flood lands exactly as it does on main (one entry port, the victim\'s router filters it)', () => {
|
||||
const { ev, errors } = load({ seed: 5 });
|
||||
remoteTransit(ev, false);
|
||||
ev("S.pops.fra.rgen=RG.findIndex(r=>r.fs===2);S.day=60;S.ev.ddos={id:'a',city:'fra',vec:'dns',gbps:200,start:S.day,until:S.day+3,entry:{k:'t',id:S.transit[0].id,lab:''},bh:false};compute()");
|
||||
// Full Flowspec leaves 15%: 30G of junk on the 100G wave, next to Frankfurt's own traffic.
|
||||
assert.ok(Math.abs(ev('R.ddos[0].leak') - 30) < 1e-9);
|
||||
assert.ok(Math.abs(ev("R.ef[edgeKey(S.links[0])].net.junk") - 30) < 1e-6);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('an attack is held or lost at its victim; other POPs and their DDoS-protected customers are not charged', () => {
|
||||
const { ev, errors } = load({ seed: 5 });
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=6;S.nextFail=1e9;S.nextEvent=1e9;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc']){S.pops[c].bb={d:50};S.pops[c].rgen=3}");
|
||||
ev("S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:0}];S.scrubs=[{city:'fra',tier:1}];S.scrubMode='always'");
|
||||
// New York is struggling on its own (a 10G port for 200G of eyeballs), and has a DDoS-protected customer.
|
||||
ev("S.pops.nyc.bb.d=200;S.biz.push({id:'sc',type:'scrub',name:'Shield',city:'nyc',bw:1,rate:1000,mood:80,since:0})");
|
||||
ev("S.day=60;S.ev.ddos={id:'a',city:'fra',vec:'http',gbps:20,start:S.day,until:S.day+3,entry:{k:'t',id:'tf',lab:''}};compute()");
|
||||
assert.ok(ev("sfOf(R,'nyc')") < 0.85, 'New York is under water anyway');
|
||||
assert.ok(ev("sfOf(R,'fra')") >= 0.97, 'the victim is fine');
|
||||
assert.equal(ev('ddosSf(S.ev.ddos)'), ev("sfOf(R,'fra')"));
|
||||
ev('dayTick()');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ev.ddos.sla||[])')), [], 'no SLA payout for a customer in another city');
|
||||
assert.equal(ev('S.stats.sla||0'), 0);
|
||||
ev('S.day=S.ev.ddos.until;ddosExpire()');
|
||||
assert.equal(ev('S.stats.ddosOk||0'), 1, 'held at the victim');
|
||||
assert.equal(ev('S.stats.ddosLost||0'), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('fourteen attacks on a big network keep the save small, and 2.0 beta saves with per-port shares still load', () => {
|
||||
const fs = require('node:fs'), path = require('node:path');
|
||||
const fx = JSON.parse(fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'));
|
||||
const { ev, errors } = load({ seed: 3 });
|
||||
ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(fx.S || fx))}));UI.started=true;compute()`);
|
||||
const before = ev('JSON.stringify(S).length');
|
||||
ev("S.day=Math.max(S.day,50);for(let i=0;i<14;i++){S.ddosStarts=[];ddosAttack(false);}compute()");
|
||||
assert.equal(ev('ddosAll().length'), 14);
|
||||
assert.ok(ev('JSON.stringify(S).length') - before < 10000, 'a few hundred bytes per attack');
|
||||
// A beta save spread each attack over every port: the shares are dropped and the attack carries on.
|
||||
ev("S.ev.ddos.entries=Array.from({length:300},(_,i)=>({k:'p',id:'x'+i,city:S.ev.ddos.city,lab:'',share:1}));S.ev.ddos.entry={k:'distributed',lab:'Distributed ingress'};S=migrate(JSON.parse(JSON.stringify(S)));compute()");
|
||||
assert.equal(ev('S.ev.ddos.entries'), undefined);
|
||||
assert.equal(ev('S.ev.ddos.entry.k'), 'edge');
|
||||
assert.equal(ev('ddosAll().length'), 14);
|
||||
assert.match(ev('ddosPanel()'), /Live attack/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('spicy chaos stretches exactly the attack (or outage) an incident is about, and saves keep it', () => {
|
||||
const { ev, errors } = load({ seed: 99 });
|
||||
ev("beginGame('R','fra',{mode:'normal',preset:'bgp'});if(UI.pendGame)ACT.pitchSkip();S.cash=1e12;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});S.links.push({id:'L',a:'fra',b:'ams',kind:'wave',tier:1,km:400,mo:1,cut:0});S.day=50");
|
||||
// A link that happens to be cut until the same day as the next attacks must stay as it is.
|
||||
ev("S.links[0].cut=S.day+2");
|
||||
for (let k = 0; k < 4; k++) ev("const old=Math.random;let n=0;Math.random=()=>n++===3?0:old();ddosAttack();Math.random=old");
|
||||
const rows = JSON.parse(ev("JSON.stringify(S.inc.filter(i=>i.type==='ddos').map(i=>[i.until,ddosAll(S,false).find(a=>a.id===i.atk).until]))"));
|
||||
assert.equal(rows.length, 4);
|
||||
for (const [inc, atk] of rows) { assert.equal(atk, inc, 'the attack lasts as long as its incident'); assert.equal(inc, 52, 'one day, stretched by half'); }
|
||||
assert.equal(ev('S.links[0].cut'), 52, 'an unrelated cut ending the same day is not stretched');
|
||||
// The longest spicy attack (7 days, stretched to 11) survives a reload.
|
||||
ev("S.ev.ddos.until=S.day+11;S=migrate(JSON.parse(JSON.stringify(S)))");
|
||||
assert.equal(ev('S.ev.ddos.until-S.day'), 11);
|
||||
ev("S.ev.ddos.until=S.day+40;S=migrate(JSON.parse(JSON.stringify(S)))");
|
||||
assert.equal(ev('S.ev.ddos.until-S.ev.ddos.start'), 11, 'but not longer');
|
||||
// Outages are found by their ref: a fiber cut stretches its own link only.
|
||||
ev("S.links.push({id:'M',a:'fra',b:'ams',kind:'wave',tier:1,km:400,mo:1,cut:S.day+4});S.links[0].cut=S.day+4;S.links[0].trench='T';addInc({type:'cut',ref:'T',until:S.day+4,msg:'x'})");
|
||||
assert.equal(ev("S.links[0].cut-S.day"), 6);
|
||||
assert.equal(ev("S.links.find(l=>l.id==='M').cut-S.day"), 4);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('BGP at 3 a.m. brings about twice On-call\'s DDoS; gaming customers bring their own, busier schedule', () => {
|
||||
const picks = {};
|
||||
for (const preset of ['oncall', 'bgp']) {
|
||||
const { ev, errors } = load({ seed: 7 });
|
||||
ev(`beginGame('R','fra',{mode:'normal',preset:'${preset}'});if(UI.pendGame)ACT.pitchSkip();S.cash=1e12;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});S.day=100;compute()`);
|
||||
// No daily attacks without gamers, spicy or not.
|
||||
ev("window.__n=0;const real=ddosAttack;ddosAttack=()=>{window.__n++;};for(let i=0;i<300;i++)ddosTick();window.__tick=window.__n;window.__n=0;for(let i=0;i<4000;i++)fireFailure();ddosAttack=real");
|
||||
assert.equal(ev('window.__tick'), 0, `${preset}: no daily DDoS schedule without gaming customers`);
|
||||
picks[preset] = ev('window.__n') * ev('chaosMul()');
|
||||
ev("S.biz.push({id:'g',type:'game',name:'G',city:'fra',bw:1,rate:1,mood:80,since:0});window.__n=0;const real=ddosAttack;ddosAttack=()=>{window.__n++;};for(let i=0;i<300;i++)ddosTick();ddosAttack=real");
|
||||
assert.ok(ev('window.__n') > 5, `${preset}: gamers attract attacks on their own schedule`);
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
const ratio = picks.bgp / picks.oncall;
|
||||
assert.ok(ratio > 1.7 && ratio < 2.3, `about twice the DDoS (${ratio.toFixed(2)}x)`);
|
||||
});
|
||||
|
||||
test('an imported save cannot put HTML in a Flood Season attacker\'s name', () => {
|
||||
const { ev, dom, errors } = load({ seed: 5 });
|
||||
ev("ACT.startScn({id:'flood',sure:1});S.day=10;ddosAttack();S.ev.ddos.who='<img src=x id=pwn>';S=migrate(JSON.parse(JSON.stringify(S)))");
|
||||
assert.equal(ev('S.ev.ddos.who'), undefined, 'only names from the list survive a load');
|
||||
ev('S.ev.ddos.who="<img src=x id=pwn2>";ddosDone(S.ev.ddos)');
|
||||
assert.equal(dom.window.document.getElementById('pwn'), null);
|
||||
assert.equal(dom.window.document.getElementById('pwn2'), null, 'and the toast escapes it anyway');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the China licence arrives in a tenth of the time with quick lead times, and the button says so', () => {
|
||||
for (const [preset, days] of [['oncall', 45], ['freeze', 5]]) {
|
||||
const { ev, errors } = load();
|
||||
ev(`beginGame('C','fra',{mode:'normal',preset:'${preset}'});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9`);
|
||||
assert.match(ev("tr('link_panels.apply_for_a_license_price_mo_n_days',{price:'$1',mo:'$1',n:leadDays(45)})"), new RegExp(`~${days} days`));
|
||||
ev('ACT.applyCn()');
|
||||
assert.equal(ev('S.cnLic.ready-S.day'), days, preset);
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
});
|
||||
|
||||
test('Flood Season escalates from ordinary floods to monsters, and empty POPs or no customers do not hold floods for free', () => {
|
||||
const { ev, errors } = load({ seed: 5 });
|
||||
ev("ACT.startScn({id:'flood',sure:1});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'ams'});ACT.buyTransit({city:'ams',net:NETS.find(n=>sellsAt(n,'ams')).id,tier:1});compute()");
|
||||
const sizes = JSON.parse(ev("const o=[];for(let i=0;i<60;i++){dayTick();for(const a of ddosAll())if(a.start===S.day)o.push(a.gbps);}JSON.stringify(o)"));
|
||||
assert.ok(sizes.some(g => g < 100), `some ordinary floods early on (${sizes.join(' ')})`);
|
||||
assert.ok(sizes.some(g => g >= 1000), 'and some terabit monsters');
|
||||
// Ten empty POPs: floods still go for Amsterdam, where the customers are.
|
||||
ev("for(const c of ['lon','par','fra','mad','mil','vie','waw','sto','osl','hel'])ACT.buildPop({city:c});compute();S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[]");
|
||||
ev("for(let i=0;i<10;i++){S.ddosStarts=[];ddosAttack(false);}");
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify([...new Set(ddosAll().map(a=>a.city))])')), ['ams']);
|
||||
// A flood on a city with nobody to serve only holds if the tools soak it up.
|
||||
ev("S.ev.ddosMore=[];S.ev.ddos={id:'e',city:'lon',vec:'http',gbps:500,start:S.day,until:S.day+2,entry:{k:'edge',lab:''}};compute()");
|
||||
assert.equal(ev("R.cityDem.lon||0"), 0);
|
||||
assert.ok(ev('ddosSf(S.ev.ddos)') < 0.97, 'unmitigated: not held');
|
||||
ev("S.scrubs=[{city:'lon',tier:1}];S.scrubMode='always';compute()");
|
||||
assert.equal(ev('ddosSf(S.ev.ddos)'), 1, 'scrubbed: held');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -47,7 +47,7 @@ test('Coax gets Spectre-um’d a year in, and Final Frontear joins Very-Zone a y
|
|||
start(ev2);
|
||||
ev2("ACT.buildPop({city:'chi'});S.pni.push({id:'a',net:'cxc',city:'chi',tier:1,ready:0},{id:'b',net:'spc',city:'chi',tier:1,ready:0});S.day=400;dayTick()");
|
||||
assert.equal(ev2("S.pni.filter(p=>p.city==='chi').map(p=>p.net).join()"), 'spc');
|
||||
// the inbox never brings requests from a brand that no longer exists, and saves keep the record
|
||||
// saves keep the record of who merged
|
||||
ev("const o=JSON.parse(JSON.stringify(S));S=migrate(o)");
|
||||
assert.equal(ev("merged('cxc')&&merged('ftr')"), true);
|
||||
ev("S.merged={cxc:'x',zzz:3};S=migrate(JSON.parse(JSON.stringify(S)))");
|
||||
|
|
|
|||
69
tests/fiber-broker.test.js
Normal file
69
tests/fiber-broker.test.js
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
// The capacity broker sells a listing as the route's market wants (#203), and consortium seats can regenerate in the
|
||||
// landing stations along their cable, so a seat bought early can be lit with early optics.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const start = (ev) => ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;S.offers=[];S.biz=[]");
|
||||
const fiber = (ev, id, a, b, km) => ev(`for(const c of ['${a}','${b}'])if(!S.pops[c])ACT.buildPop({city:c});S.links.push({id:'${id}',a:'${a}',b:'${b}',kind:'df',own:true,sys:'roadm',ch:['tp16'],km:${km},ready:0,day:0,cut:0,mo:100,trench:'own:${id}',pairs:1,spares:false});compute()`);
|
||||
|
||||
test('a route\'s market follows the eyeballs at both ends, and a landing town counts the city it serves', () => {
|
||||
const { ev } = load();
|
||||
start(ev);
|
||||
assert.ok(ev("brMarket('fra','ams')") >= 6, 'Frankfurt to Amsterdam wants a handful of waves');
|
||||
assert.equal(ev("brMarket('jed','gdx')"), 1, 'Jeddah to Magadan (#203) wants about one');
|
||||
assert.ok(ev("brMarket('nyc','bde')") > 10, 'Bude lands the Atlantic for London');
|
||||
assert.ok(ev("brMarket('nyc','bde')") > ev("brMarket('nyc','gdx')"));
|
||||
});
|
||||
|
||||
test('a listing sells over time, never past the market, and rent from a road to nowhere stays small', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
fiber(ev, 'big', 'fra', 'ams', 450);
|
||||
fiber(ev, 'far', 'jed', 'gdx', 9089);
|
||||
ev("__reseed(7);ACT.listFiber({id:'big',w:60});ACT.listFiber({id:'far',w:60})");
|
||||
assert.equal(ev("S.biz.length"), 0, 'nothing sells the moment it is listed');
|
||||
ev('for(let d=0;d<720;d++)brTick()');
|
||||
const sold = (id) => ev(`S.biz.filter(b=>b.link==='${id}').reduce((a,b)=>a+(b.slots||0),0)`);
|
||||
assert.ok(sold('big') >= 3, `Frankfurt–Amsterdam sold ${sold('big')}`);
|
||||
assert.ok(sold('big') <= ev("brMarket('fra','ams')"), 'never more than the route wants');
|
||||
assert.equal(sold('far'), 1, 'Jeddah–Magadan: one wave, then the market is full');
|
||||
assert.equal(ev("brFree(S.links.find(l=>l.id==='far'))"), 0);
|
||||
// random alien-wave offers respect the market too
|
||||
ev("S.offers=[];for(let i=0;i<400;i++)spawnOffer()");
|
||||
assert.equal(ev("S.offers.filter(o=>o.link==='far').length"), 0, 'no random offer for a full route');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a listing is kept in the save, checked, and can be taken off the market', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
fiber(ev, 'big', 'fra', 'ams', 450);
|
||||
ev("ACT.listFiber({id:'big',w:4})");
|
||||
ev("const t=JSON.stringify(packSave(S));S=migrate(JSON.parse(t))");
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.find(l=>l.id==='big').list)")), { w: 4, p: 0 });
|
||||
ev("const o=JSON.parse(JSON.stringify(packSave(S)));o.links.find(l=>l.id==='big').list={w:'lots',p:-3};S=migrate(o)");
|
||||
assert.equal(ev("S.links.find(l=>l.id==='big').list===undefined"), true, 'junk is dropped');
|
||||
ev("ACT.listFiber({id:'big',w:2});ACT.unlistFiber({id:'big'})");
|
||||
assert.equal(ev("S.links.find(l=>l.id==='big').list===undefined"), true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a consortium seat regenerates in the landing stations along its cable, so early optics can light it', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
ev("S.lvl=2;for(const c of ['mrs','sin'])if(!S.pops[c])ACT.buildPop({city:c});S.pops.mrs.rgen=S.pops.sin.rgen=1;S.seatOff={a:'mrs',b:'sin',name:'Sea, Me, We, Us, Them',km:seatKm('mrs','sin'),exp:S.day+30};ACT.seatBuy({n:1});const l=S.links.at(-1);l.ready=S.day;compute()");
|
||||
const id = ev('S.links.at(-1).id');
|
||||
assert.ok(ev(`!!chWhy(S.links.at(-1),'zr4')`), 'out of reach without regens');
|
||||
for (let i = 0; i < 8; i++) ev(`ACT.regen({id:'${id}',d:1})`);
|
||||
assert.equal(ev('S.links.at(-1).regen'), 8, 'regen sites on a seat');
|
||||
assert.equal(ev(`chWhy(S.links.at(-1),'zr4')`), '', 'and the level-2 optic reaches');
|
||||
ev(`ACT.addCh({id:'${id}',o:'zr4'})`);
|
||||
assert.equal(ev('S.links.at(-1).ch.length'), 1, 'lit');
|
||||
ev(`selectLink(S.links.at(-1));renderPanel()`);
|
||||
assert.match(ev("document.getElementById('panelBody').textContent"), /landing stations along the way/);
|
||||
// your own point-to-point cable still cannot
|
||||
ev("S.links.push({id:'own',a:'lis',b:'for',kind:'df',own:true,sub:true,seaDesign:'standard',sys:'roadm',ch:[],km:6000,ready:0,day:0,cut:0,mo:1,trench:'own:own',pairs:1});ACT.regen({id:'own',d:1})");
|
||||
assert.equal(ev("S.links.find(l=>l.id==='own').regen|0"), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -2,6 +2,16 @@ const test = require('node:test');
|
|||
const assert = require('node:assert/strict');
|
||||
const { load, seed } = require('./harness');
|
||||
|
||||
test('daily DDoS spawns share one routing calculation and score their first active day', () => {
|
||||
const { ev, errors } = load();
|
||||
// The busier daily DDoS schedule comes with gaming customers.
|
||||
ev("ACT.start({});S.biz=[{type:'game',id:'g',name:'G',city:'fra',bw:1,rate:1,reqs:[]}];S.cash=1e9;S.day=50;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute();window.__compute=compute;window.__random=Math.random;window.__computes=0;compute=()=>{window.__computes++;window.__compute()};Math.random=()=>0;dayTick();compute=window.__compute;Math.random=window.__random");
|
||||
assert.equal(ev('ddosAll().length'), 2, 'both daily spawn opportunities were used');
|
||||
assert.equal(ev('window.__computes'), 1, 'daily spawns do not reroute the whole network individually');
|
||||
assert.ok(ev('ddosAll().every(a=>a.worst===ddosSf(a))'), 'first-day service is recorded after routing');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('page boots to the title screen without errors', () => {
|
||||
const { ev, errors } = load();
|
||||
assert.equal(ev("document.getElementById('modal').hidden"), false);
|
||||
|
|
@ -197,6 +207,45 @@ test('Flowspec is a router-model capability, and each tool answers a flood', ()
|
|||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a distributed SYN flood reports actual Flowspec drops and sends only the remainder to scrubbing', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.scrubs=[{city:'fra',tier:0}];S.scrubMode='always';S.ev.ddos={id:'syn',city:'fra',vec:'syn',gbps:30.2,start:0,until:7,entry:{k:'edge',lab:''}};compute()");
|
||||
assert.equal(ev('ddosReport(S.ev.ddos).flowspec'), 0);
|
||||
assert.equal(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned'), 30.2);
|
||||
assert.match(ev('ddosPanel()'), /— No Flowspec filtering: ingress routers have no TCAM/);
|
||||
assert.match(ev('ddosPanel()'), /✓ Scrubbing in Frankfurt: 30\.2 Gbps \/ 100G/);
|
||||
assert.doesNotMatch(ev('ddosPanel()'), /✓ Flowspec|After upstream scrubbing|Reaching your network/);
|
||||
for (const [router, dropped, scrubbed] of [[1,18.12,12.08], [3,25.67,4.53]]) {
|
||||
ev(`S.pops.fra.rgen=${router};compute()`);
|
||||
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-dropped)<1e-9);
|
||||
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned')-scrubbed)<1e-9);
|
||||
assert.match(ev('ddosPanel()'), new RegExp('✓ Flowspec dropping: '+dropped.toFixed(1).replace('.', '\\.')+' Gbps'));
|
||||
assert.match(ev('ddosPanel()'), new RegExp('Scrubbing in Frankfurt: '+scrubbed.toFixed(1).replace('.', '\\.')+' Gbps / 100G'));
|
||||
assert.doesNotMatch(ev('ddosPanel()'), /no TCAM|Edge filters dropping/);
|
||||
}
|
||||
ev("S.ev.ddos.vec='ack';compute()");
|
||||
assert.equal(ev('ddosReport(S.ev.ddos).flowspec'), 0);
|
||||
assert.equal(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned'), 30.2);
|
||||
assert.match(ev('ddosPanel()'), /— Flowspec cannot catch ACK flood/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('Flowspec, upstream cleaning and other edge filters are each accounted for separately', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=6;S.pops.fra.rgen=1;S.transit=[{id:'tf',city:'fra',net:'cog',tier:1}];S.scrubs=[{city:'fra',tier:0}];S.ev.ddos={id:'syn',city:'fra',vec:'syn',gbps:30.2,start:0,until:7,entry:{k:'t',id:'tf'}};compute()");
|
||||
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-18.12)<1e-9);
|
||||
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned')-12.08)<1e-9);
|
||||
assert.match(ev('ddosPanel()'), /✓ Flowspec dropping: 18\.1 Gbps/);
|
||||
ev('S.transit[0].clean=true;compute()');
|
||||
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).reaching')-3.02)<1e-9, 'clean pipe leaves a tenth');
|
||||
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-1.812)<1e-9);
|
||||
assert.match(ev('ddosPanel()'), /✓ After upstream scrubbing: 3\.0 Gbps/);
|
||||
ev("S.ixp={fra:1};S.ev.ddos.ixbh=true;compute()");
|
||||
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).filtered-ddosReport(S.ev.ddos).flowspec')-0.604)<1e-9);
|
||||
assert.match(ev('ddosPanel()'), /✓ Edge filters dropping: 0\.6 Gbps/);
|
||||
assert.ok(ev('Math.abs(ddosReport(S.ev.ddos).reaching-ddosReport(S.ev.ddos).filtered-ddosReport(S.ev.ddos).sp.parts.reduce((n,x)=>n+x.cleaned,0)-ddosReport(S.ev.ddos).leak)<1e-9'));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
test('RTBH blackholes the victim, and HackBack 3000 is a gamble', () => {
|
||||
const { ev } = load();
|
||||
ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=120;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()");
|
||||
|
|
@ -420,10 +469,6 @@ test('notifications: the NOC keeps the last ten minutes, folds repeats and opens
|
|||
const os = JSON.parse(ev("JSON.stringify(S.log.map(e=>e.o))"));
|
||||
assert.deepEqual(os, [null, { a: 'city', v: 'lon' }, { a: 'link', v: linkId }, { a: 'city', v: 'fra' }]);
|
||||
assert.equal(ev("S.log[0].h"), 'Raffle'); assert.equal(ev("S.log[0].t"), 'Raffle You won a T-shirt.');
|
||||
// the peering inbox's own button opens the peering inbox
|
||||
ev("toast('<b>Peering request</b><br>From a small network.','',[{l:'Inbox',act:'inbox',args:{}}])");
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.log[0].o)')), { a: 'inbox' });
|
||||
ev('ACT.logOpen({id:S.log[0].id})'); assert.equal(ev("$('modal').hidden"), false, 'the inbox opens');ev('closeModal();S.log.shift()');
|
||||
// an incident points at what broke
|
||||
assert.deepEqual(JSON.parse(ev(`JSON.stringify(incOpen({ref:'${linkId}'}))`)), { a: 'link', v: linkId });
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(incOpen({ref:S.links[0].trench||S.links[0].id}))")), { a: 'link', v: ev('S.links[0].id') });
|
||||
|
|
@ -434,14 +479,13 @@ test('notifications: the NOC keeps the last ten minutes, folds repeats and opens
|
|||
assert.equal(ev("S.log.length"), 6, 'a minute later it starts a new line');
|
||||
// the NOC shows them right after the incidents, with Open where there is something to open
|
||||
assert.equal(ev("logUnread()"), 6);
|
||||
ev("renderHUD()"); assert.equal(doc.getElementById('hNocNew').hidden, false); assert.equal(doc.getElementById('hNocNew').textContent, '6');
|
||||
ev("renderHUD()"); assert.equal(doc.getElementById('hNocNew').hidden, true, 'no unread count on the NOC button (2.0)');
|
||||
ev("UI.left='noc';UI.leftOpen=true;UI.sel=null;renderLeft();renderHUD()");
|
||||
const body = doc.getElementById('leftBody').textContent;
|
||||
assert.match(body, /Notifications\s*last 10 minutes/);
|
||||
assert.ok(body.indexOf('Notifications') < body.indexOf('DDoS scrubbing'), 'near the top, not at the bottom');
|
||||
assert.match(body, /×5/); assert.match(body, /just now/);
|
||||
assert.equal(doc.querySelectorAll('#leftBody [data-act=logOpen]').length, 2, 'Open only where it leads somewhere (2 of the 5 shown)');
|
||||
assert.equal(doc.getElementById('hNocNew').hidden, true, 'read once the NOC is open');
|
||||
assert.equal(ev("logUnread()"), 0);
|
||||
ev("ACT.logAll()"); assert.equal(doc.querySelectorAll('#leftBody .note').length, 6); assert.equal(doc.querySelectorAll('#leftBody [data-act=logOpen]').length, 3);
|
||||
// Open goes there
|
||||
|
|
@ -457,12 +501,15 @@ test('notifications: the NOC keeps the last ten minutes, folds repeats and opens
|
|||
ev("S.log.push({t:'old',k:'weird',o:{a:'city',v:'atlantis'},n:'many'},{t:5},{t:'x',o:{a:'tab',v:'evil'}},{t:'y',o:{a:'link',v:'l1'},at:'soon'});S=sanitize(S)");
|
||||
const tail = JSON.parse(ev("JSON.stringify(S.log.slice(-3))"));
|
||||
assert.deepEqual(tail.map(e => [e.t, e.k, e.o, e.n, e.at]), [['old', '', null, 1, 0], ['x', '', null, 1, 0], ['y', '', { a: 'link', v: 'l1' }, 1, 0]]);
|
||||
// phones: the NOC tab carries the count
|
||||
// phones: the NOC tab shows no numbers, only a red dot while something is broken
|
||||
ev("__tick(1000);toast('<b>Router crashed</b><br>Your router in London is rebooting.','bad');UI.left='goals';UI.leftOpen=false");
|
||||
dom.window.innerWidth = 360; ev("renderAll&&renderAll()");
|
||||
const nocTab = [...doc.querySelectorAll('#tabbar [data-act=phoneTab]')].find(b => JSON.parse(b.dataset.args).t === 'noc');
|
||||
assert.equal(nocTab.querySelector('.cnt').textContent, '1', 'one unread notification on the NOC tab');
|
||||
assert.equal(nocTab.querySelector('.cnt').classList.contains('red'), false, 'not red: red is for incidents');
|
||||
assert.equal(nocTab.querySelector('.cnt'), null, 'no number for unread notifications on the NOC tab');
|
||||
ev("S.inc.push({id:'x1',type:'crash',city:'lon',msg:'',until:S.day+3});renderAll()");
|
||||
const nocTab2 = [...doc.querySelectorAll('#tabbar [data-act=phoneTab]')].find(b => JSON.parse(b.dataset.args).t === 'noc');
|
||||
assert.ok(nocTab2.querySelector('.cnt.dot.red'), 'a live incident shows a red dot');
|
||||
assert.equal(nocTab2.querySelector('.cnt').textContent, '', 'and no number');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
|
@ -478,3 +525,549 @@ test('the broadband panel shows what homes in that city really pay, not the base
|
|||
assert.ok(ev("cityPanel('del')").includes(rev + '/mo'), `revenue line matches what the month pays (${rev})`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// Custom routing metrics: a fra–ams–par triangle where the direct fra–par link is normally shortest.
|
||||
const triangle = (ev) => {
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
|
||||
ev("for(const c of ['ams','par'])ACT.buildPop({city:c});const L=(a,b)=>{UI.via=null;openLinkModal(a,b);ACT.buildLink({tier:1});closeModal();};L('fra','ams');L('ams','par');L('fra','par');compute()");
|
||||
ev("window.FP=S.links.find(l=>(l.a==='fra'&&l.b==='par')||(l.a==='par'&&l.b==='fra')).id;window.FK=edgeKey(S.links.find(l=>l.id===FP));window.pmOf=()=>S.pairMet[FK];window.hops=()=>JSON.stringify(trPaths('fra').path('par').map(h=>h.l.id))");
|
||||
};
|
||||
|
||||
test('a custom multiplier routes exactly like the matching preset', () => {
|
||||
const { ev, errors } = load();
|
||||
triangle(ev);
|
||||
assert.equal(ev("hops()"), JSON.stringify([ev("FP")]), 'direct link wins by default');
|
||||
ev("ACT.setMetric({id:FP,v:'avoid'})");
|
||||
const avoid = ev("JSON.stringify({h:hops(),load:R.load,served:R.served})");
|
||||
ev("ACT.setMetric({id:FP,v:'custom'})");
|
||||
assert.equal(ev("pairMet(FK)"), 'custom');
|
||||
const m = ev("pmOf()");
|
||||
assert.equal(m.k, 'f');
|
||||
assert.equal(m.v, 4, 'custom starts from the preset it replaces');
|
||||
assert.equal(ev("JSON.stringify({h:hops(),load:R.load,served:R.served})"), avoid);
|
||||
ev("ACT.setMetric({id:FP,v:'normal'})");
|
||||
assert.equal(ev("FK in S.pairMet"), false, 'presets drop the custom metric');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('an absolute custom cost steers the path, and switching modes keeps the cost', () => {
|
||||
const { ev, errors } = load();
|
||||
triangle(ev);
|
||||
ev("ACT.setMetric({id:FP,v:'custom'});ACT.metricMode({id:FP,k:'w'})");
|
||||
const l = ev("S.links.find(l=>l.id===FP)");
|
||||
assert.equal(ev("pmOf().k"), 'w');
|
||||
assert.equal(ev("pmOf().v"), Math.round(l.km + 60), 'switching to cost keeps the effective metric');
|
||||
ev("ACT.selLink({id:FP});renderAll();$('metIn').value='65535';ACT.metricSet({id:FP})");
|
||||
assert.equal(ev("pmOf().v"), 65535);
|
||||
assert.ok(!JSON.parse(ev("hops()")).includes(ev("FP")), 'a huge cost sends traffic round via Amsterdam');
|
||||
ev("renderAll();$('metIn').value='1';ACT.metricSet({id:FP})");
|
||||
assert.equal(ev("hops()"), JSON.stringify([ev("FP")]));
|
||||
ev("ACT.metricMode({id:FP,k:'f'})");
|
||||
assert.equal(ev("pmOf().v"), 0.1, 'converted back to a multiplier, clamped to the minimum');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('custom metric input is validated and clamped', () => {
|
||||
const { ev, errors } = load();
|
||||
triangle(ev);
|
||||
ev("ACT.setMetric({id:FP,v:'custom'});ACT.selLink({id:FP});renderAll()");
|
||||
ev("$('metIn').value='';ACT.metricSet({id:FP})");
|
||||
assert.equal(ev("pmOf().v"), 1, 'empty input changes nothing');
|
||||
ev("renderAll();$('metIn').value='9999';ACT.metricSet({id:FP})");
|
||||
assert.equal(ev("pmOf().v"), 100);
|
||||
ev("renderAll();$('metIn').value='0';ACT.metricSet({id:FP})");
|
||||
assert.equal(ev("pmOf().v"), 0.1);
|
||||
ev("ACT.metricMode({id:FP,k:'x'});ACT.setMetric({id:FP,v:'bogus'})");
|
||||
assert.equal(ev("pairMet(FK)"), 'custom');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('custom metrics survive a save, and broken ones are repaired', () => {
|
||||
const { ev, errors } = load();
|
||||
triangle(ev);
|
||||
ev("ACT.setMetric({id:FP,v:'custom'});ACT.metricMode({id:FP,k:'w'});pmOf().v=777;S=migrate(JSON.parse(JSON.stringify(S)));compute()");
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(pmOf())")), { k: 'w', v: 777 });
|
||||
ev("S.pairMet[FK]={k:'zz',v:'lots'};S=migrate(JSON.parse(JSON.stringify(S)));compute()");
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(pmOf())")), { k: 'f', v: 1 });
|
||||
ev("S.pairMet[FK]={k:'w',v:1e9};S=migrate(JSON.parse(JSON.stringify(S)))");
|
||||
assert.equal(ev("pmOf().v"), 65535);
|
||||
// An old save: a preset metric on the link itself, from before metrics moved to the city pair.
|
||||
ev("delete S.pairMet[FK];S.links.find(l=>l.id===FP).metric='avoid';S=migrate(JSON.parse(JSON.stringify(S)));compute()");
|
||||
assert.equal(ev("pmOf()"), 'avoid');
|
||||
assert.equal(ev("'metric' in S.links.find(l=>l.id===FP)"), false);
|
||||
assert.equal(JSON.parse(ev("hops()")).length, 2, 'the old save still routes, avoiding the direct link');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('preset buttons stay plain, and Custom explains the numbers, also on phones', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
triangle(ev);
|
||||
for (const w of [1280, 390]) {
|
||||
ev(`window.innerWidth=${w};ACT.setMetric({id:FP,v:'normal'});ACT.selLink({id:FP});renderAll()`);
|
||||
const doc = dom.window.document;
|
||||
const btns = [...doc.querySelectorAll('#panel [data-act="setMetric"]')];
|
||||
assert.equal(btns.length, 5);
|
||||
const km = ev("S.links.find(l=>l.id===FP).km");
|
||||
assert.deepEqual(btns.map(b => b.textContent), ['Prefer', 'Normal', 'Avoid', 'Backup only', 'Custom']);
|
||||
assert.equal(doc.getElementById('metIn'), null);
|
||||
assert.doesNotMatch(doc.getElementById('panel').textContent, /times a multiplier/);
|
||||
ev("ACT.setMetric({id:FP,v:'custom'})");
|
||||
assert.ok(doc.getElementById('metIn'), `custom editor at ${w}px`);
|
||||
assert.ok(doc.querySelector('#panel [data-act="metricMode"]'));
|
||||
const txt = doc.getElementById('panel').textContent;
|
||||
assert.match(txt, /times a multiplier/);
|
||||
assert.match(txt, new RegExp(`Normal ×1 = ${Math.round(km + 60)}, Avoid ×4 = ${Math.round((km + 60) * 4)}`));
|
||||
assert.match(txt, /Multiplier: scales the distance cost/);
|
||||
assert.match(txt, /Cost on this link/);
|
||||
ev("ACT.metricMode({id:FP,k:'w'})");
|
||||
assert.match(doc.getElementById('panel').textContent, /Cost: the exact number/);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a custom metric belongs to the city pair, like the presets, and a standby link keeps it', () => {
|
||||
const { ev, errors } = load();
|
||||
triangle(ev);
|
||||
ev("UI.via=null;openLinkModal('fra','par');ACT.buildLink({tier:1});closeModal();compute()");
|
||||
ev("ACT.setMetric({id:FP,v:'custom'});ACT.metricMode({id:FP,k:'w'});ACT.selLink({id:FP});renderAll();$('metIn').value='65535';ACT.metricSet({id:FP})");
|
||||
const other = ev("S.links.find(l=>l.id!==FP&&edgeKey(l)===FK).id");
|
||||
assert.equal(ev(`pairMet(edgeKey(S.links.find(l=>l.id==='${other}')))`), 'custom', 'the second link between the cities shares it');
|
||||
ev(`ACT.setStandby({id:'${other}',on:1})`);
|
||||
assert.ok(!JSON.parse(ev("hops()")).includes(ev("FP")), 'the pair is still avoided');
|
||||
assert.equal(ev("pmOf().v"), 65535);
|
||||
// Removing every link of the pair drops the metric with it.
|
||||
ev("S.links=S.links.filter(l=>edgeKey(l)!==FK);prunePairMet()");
|
||||
assert.equal(ev("FK in S.pairMet"), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
||||
test('Memcached amplification and ACK flood are available without gaming customers and respect Flowspec', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});RG[0].fs=2");
|
||||
assert.equal(ev('S.biz.length'), 0);
|
||||
assert.equal(ev('DDOS_VEC.memcached.fs'), true);
|
||||
assert.equal(ev('DDOS_VEC.ack.fs'), false);
|
||||
ev("S.ev.ddos={city:'fra',vec:'ack',gbps:300,until:S.day+3,start:S.day};compute()");
|
||||
const ack = ev('R.served');
|
||||
assert.match(ev('ddosPanel()'), /ACK flood/);
|
||||
assert.doesNotMatch(ev('ddosPanel()'), /application layer/);
|
||||
ev("S.ev.ddos.vec='memcached';compute()");
|
||||
assert.ok(ev('R.served') > ack, 'Flowspec filters Memcached but cannot filter ACK');
|
||||
for (const vec of ['memcached', 'ack']) {
|
||||
ev(`const old=Math.random;Math.random=()=>(${['dns','ntp','memcached','ack'].indexOf(vec)}+0.1)/ddosVectors().length;ddosAttack();Math.random=old`);
|
||||
assert.equal(ev('ddosAll().at(-1).vec'), vec, 'the generator can select each new vector');
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
||||
test('DDoS accounting conserves attack bandwidth through upstream, edge and local scrubbing', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});S.pops.fra.bb.d=100;S.scrubs=[{city:'fra',tier:1}];S.transit[0].clean=true;S.ev.ddos={city:'fra',vec:'http',gbps:1842,until:5,start:0,entry:{k:'t',id:S.transit[0].id}};compute()");
|
||||
assert.ok(Math.abs(ev('R.ddos[0].reaching') - 184.2) < 1e-9);
|
||||
assert.equal(ev('R.ddos[0].sp.parts[0].cleaned'), ev('R.ddos[0].reaching'));
|
||||
assert.equal(ev('R.ddos[0].leak'), 0, 'the 1T center cleans the upstream remainder');
|
||||
assert.doesNotMatch(ev('ddosPanel()'), /842 Gbps of attack traffic leaks/);
|
||||
ev('S.transit[0].clean=false;compute()');
|
||||
assert.equal(ev('R.ddos[0].reaching'), 1842);
|
||||
assert.equal(ev('R.ddos[0].leak'), 842);
|
||||
for (const setup of ["S.transit[0].clean=true", "RG[0].fs=2;S.ev.ddos.vec='dns'", "S.scrubs=[]"]) {
|
||||
ev(setup+';compute()');
|
||||
assert.ok(ev('Math.abs(R.ddos[0].reaching-R.ddos[0].filtered-(R.ddos[0].sp?.parts.reduce((n,x)=>n+x.cleaned,0)||0)-R.ddos[0].leak)<1e-9'));
|
||||
assert.ok(ev('R.ddos[0].leak<=R.ddos[0].reaching'));
|
||||
}
|
||||
// On-demand diversion must also work for an attack which began on day zero.
|
||||
ev("S.scrubs=[{city:'fra',tier:1}];S.scrubMode='ondemand';S.day=2;compute()");
|
||||
assert.equal(ev('R.ddos[0].leak'), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
||||
test('the NOC integrates DDoS mitigation totals into each live attack card without duplicate summaries on phones', () => {
|
||||
const { ev, errors, dom } = load();
|
||||
ev('ACT.start({})');
|
||||
Object.defineProperty(dom.window, 'innerWidth', { value: 360, configurable: true });
|
||||
ev("S.cash=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.transit[0].clean=true;S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={city:'fra',vec:'http',gbps:3840,until:5,start:0,entry:{k:'t',id:S.transit[0].id}};compute();UI.left='noc';UI.leftOpen=true;renderLeft()");
|
||||
const card = () => dom.window.document.querySelector('[data-act="rtbh"], [data-act="unrtbh"]').closest('.inc');
|
||||
const text = () => card().textContent;
|
||||
assert.match(card().querySelector('.nm').textContent, /🚨 Live attack: Frankfurt/);
|
||||
assert.equal(dom.window.document.querySelector('.ddos-stats'), null, 'use the existing attack card');
|
||||
assert.doesNotMatch(text(), /DDoS mitigation status|Attack size:|3840 Gbps|This attack:/);
|
||||
assert.equal(text().match(/3\.84 Tbps/g).length, 1, 'the attack size appears once');
|
||||
assert.match(text(), /✓ After upstream scrubbing: 384 Gbps/);
|
||||
assert.equal(text().match(/After upstream scrubbing/g).length, 1, 'show the upstream remainder once');
|
||||
assert.doesNotMatch(text(), /Reaching your network|reaching your network|Upstream scrubbing active/);
|
||||
assert.match(text(), /✓ Scrubbing in Frankfurt: 384 Gbps \/ 1T/);
|
||||
assert.match(text(), /✓ Attack fully mitigated/);
|
||||
ev('S.transit[0].clean=false;compute();renderLeft()');
|
||||
assert.doesNotMatch(text(), /After upstream scrubbing|Reaching your network/);
|
||||
assert.equal(text().match(/3\.84 Tbps/g).length, 1, 'inactive upstream scrubbing does not repeat the attack size');
|
||||
assert.match(text(), /✓ Scrubbing in Frankfurt: 1\.00 Tbps \/ 1T/);
|
||||
assert.match(text(), /~ 2\.84 Tbps is leaking through/);
|
||||
assert.equal(text().match(/leaking through/g).length, 1, 'show the mitigation outcome once');
|
||||
assert.doesNotMatch(text(), /Upstream scrubbing|Attack fully mitigated|leaks past mitigation/);
|
||||
ev("S.transit[0].clean=true;S.pops.fra.rgen=3;S.ev.ddos.vec='dns';compute();renderLeft()");
|
||||
assert.match(text(), /✓ Flowspec dropping: 326 Gbps/);
|
||||
assert.doesNotMatch(text(), /Edge filters dropping/);
|
||||
assert.match(text(), /✓ Scrubbing in Frankfurt: 57\.6 Gbps \/ 1T/);
|
||||
assert.match(text(), /✓ Attack fully mitigated/);
|
||||
ev('ACT.rtbh();renderLeft()');
|
||||
assert.match(text(), /~ Blackholed: the junk is gone, and so is Frankfurt/);
|
||||
assert.equal(text().match(/Blackholed:/g).length, 1);
|
||||
assert.doesNotMatch(text(), /After upstream scrubbing|reaching your network|scrubbing in Frankfurt|Attack fully mitigated|leaking through/i);
|
||||
assert.ok(card().querySelector('[data-act="unrtbh"]'), 'the existing controls stay in the card');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('overlapping floods share scrubbing capacity, have separate controls, and finish independently', () => {
|
||||
const { ev, errors, dom } = load();
|
||||
ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={id:'one',city:'fra',vec:'http',gbps:700,start:0,until:3};S.ev.ddosMore=[{id:'two',city:'fra',vec:'http',gbps:700,start:0,until:5}];compute();UI.left='noc';UI.leftOpen=true;renderLeft()");
|
||||
assert.equal(ev('R.ddos.length'), 2);
|
||||
assert.equal(ev('R.ddos.reduce((n,m)=>n+(m.sp?.parts.reduce((v,x)=>v+x.cleaned,0)||0),0)'), 1000);
|
||||
assert.equal(ev('R.ddos.reduce((n,m)=>n+m.leak,0)'), 400, 'one center cannot spend its capacity twice');
|
||||
const cards = [...dom.window.document.querySelectorAll('[data-act="rtbh"]')].map(b=>b.closest('.inc'));
|
||||
assert.equal(cards.length, 2);
|
||||
assert.match(cards[1].textContent, /✓ Scrubbing in Frankfurt: 1\.00 Tbps \/ 1T · This attack: 300 Gbps/);
|
||||
ev("ACT.rtbh({id:'two'})");
|
||||
assert.equal(ev("S.ev.ddos.bh||false"), false, 'the selected attack gets the control');
|
||||
assert.equal(ev('S.ev.ddosMore[0].bh'), true);
|
||||
assert.ok(ev('R.ddos.every(m=>m.leak===0)'), 'blackholing a target city drops every flood to it');
|
||||
ev("ACT.unrtbh({id:'one'});const old=Math.random;Math.random=()=>0.1;ACT.hackback({id:'two'});Math.random=old");
|
||||
assert.equal(ev('ddosAll().length'), 1, 'hack-back ends only the selected attack');
|
||||
ev('S.day=3;ddosExpire();compute()');
|
||||
assert.equal(ev('ddosAll().length'), 0);
|
||||
assert.equal(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)'), 2, 'both attacks scored once');
|
||||
ev('ddosExpire()');
|
||||
assert.equal(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)'), 2);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('overlapping DDoS saves round trip and legacy attacks migrate safely', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.ev.ddos={city:'fra',vec:'dns',gbps:'80',until:7,start:0};delete S.ev.ddosMore;delete S.ddosStarts;S=migrate(JSON.parse(JSON.stringify(S)))");
|
||||
assert.equal(ev('ddosAll().length'), 1);
|
||||
assert.equal(ev('S.ev.ddos.gbps'), 80);
|
||||
assert.equal(ev('S.ev.ddosMore.length'), 0);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosStarts)')), [0]);
|
||||
ev("S.ev.ddosMore=[{id:'overlap',city:'fra',vec:'ack',gbps:50,until:5,start:0,sla:['customer']},null,{city:'bad',vec:'dns'}, {city:'fra',vec:'unknown'}];S.ddosStarts=[0,'bad',Infinity,-9,99];S=migrate(JSON.parse(JSON.stringify(S)))");
|
||||
assert.equal(ev('ddosAll().length'), 2);
|
||||
assert.equal(ev('S.ev.ddosMore[0].id'), 'overlap');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosStarts)')), [0]);
|
||||
ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()');
|
||||
assert.equal(ev('R.ddos.length'), 2);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('simultaneous attacks each bill their protected customer only once', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.biz=[{id:'protected',name:'Shield',city:'fra',type:'scrub',bw:5,rate:900,mood:100,since:0,reqs:[]}];S.ev.ddos={id:'one',city:'fra',vec:'http',gbps:6000,start:0,until:7};S.ev.ddosMore=[{id:'two',city:'fra',vec:'http',gbps:6000,start:0,until:7}];compute();dayTick()");
|
||||
assert.equal(ev('S.stats.sla'), 2, 'same-day attacks have separate SLA identities');
|
||||
ev('S=migrate(JSON.parse(JSON.stringify(S)));dayTick()');
|
||||
assert.equal(ev('S.stats.sla'), 2, 'reloading does not pay the same credits twice');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('DDoS frequency rises with level and signed gaming customers, with a rolling weekly ceiling', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.day=50;S.lvl=1;S.biz=[]");
|
||||
const base = ev('ddosRate()');
|
||||
assert.equal(base, 0.5);
|
||||
ev('S.lvl=13');
|
||||
assert.equal(ev('ddosRate()'), base, 'level alone does not increase the non-gaming rate');
|
||||
ev("S.biz=[{type:'game',city:'fra'}];S.lvl=1");
|
||||
const early = ev('ddosRate()');
|
||||
ev('S.lvl=13');
|
||||
const level = ev('ddosRate()');
|
||||
ev("S.biz=Array.from({length:20},(_,i)=>({type:i%2?'cgame':'game',city:'fra'}))");
|
||||
const gaming = ev('ddosRate()');
|
||||
assert.ok(base < early && early < level && level < gaming && gaming <= 7);
|
||||
ev("S.offers=Array.from({length:50},()=>({type:'game'}));S.biz=[];S.lvl=1");
|
||||
assert.equal(ev('ddosRate()'), base, 'unsigned offers do not attract attacks');
|
||||
// Force every random spawn opportunity (gamers on board), then verify each rolling seven-day window.
|
||||
ev("S.biz=[{type:'game',city:'fra'}];");
|
||||
ev('window.__starts=[];window.__oldRandom=Math.random;Math.random=()=>0');
|
||||
for (let day = 50; day < 66; day++) {
|
||||
ev(`S.day=${day};ddosTick();window.__starts.push(...ddosAll().filter(a=>a.start===S.day).map(a=>a.start))`);
|
||||
assert.ok(ev('S.ddosStarts.length') <= 14);
|
||||
}
|
||||
ev('Math.random=window.__oldRandom');
|
||||
const starts = JSON.parse(ev('JSON.stringify(window.__starts)'));
|
||||
for (let day = 50; day < 66; day++) assert.ok(starts.filter(d=>d>day-7&&d<=day).length <= 14);
|
||||
assert.ok(starts.length > 14, 'the allowance renews as starts leave the rolling window');
|
||||
ev('for(let i=0;i<30;i++)ddosAttack()');
|
||||
assert.equal(ev('S.ddosStarts.length'), 14, 'manual and incident starts cannot bypass the cap');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('DDoS sizes use a smaller non-gaming baseline and preserve unbounded Flood Season scaling', () => {
|
||||
const { ev, errors } = load();
|
||||
ev('ACT.start({});S.lvl=13;R.demand=150000;S.biz=[]');
|
||||
assert.equal(ev('ddosSizeMean()'), 20000);
|
||||
ev('R.demand=300000');
|
||||
assert.equal(ev('ddosSizeMean()'), 40000, 'larger networks can draw still larger attacks');
|
||||
ev('S.lvl=1');
|
||||
const early = ev('ddosSizeMax()');
|
||||
ev('S.lvl=13');
|
||||
const late = ev('ddosSizeMax()');
|
||||
ev("S.biz=[{type:'game',city:'fra'}]");
|
||||
assert.ok(early < late && late < ev('ddosSizeMax()'));
|
||||
// Fixed quantiles show longer durations as both level and gaming exposure rise.
|
||||
ev('window.__oldRandom=Math.random;Math.random=()=>0.95;S.lvl=1;S.biz=[];ddosAttack();window.__earlyDur=ddosAll().at(-1).until-S.day;S.lvl=13;S.biz=Array.from({length:40},()=>({type:\'game\',city:\'fra\',bw:0,rate:0}));ddosAttack();Math.random=window.__oldRandom');
|
||||
assert.ok(ev('ddosAll().at(-1).until-S.day') > ev('window.__earlyDur'));
|
||||
assert.equal(ev('ddosAll().at(-1).until-S.day'), 7);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('scrubbing hauls retain their real source on each link when several cities use one center', () => {
|
||||
const { ev, errors, dom } = load();
|
||||
ev(`ACT.start({});S.cash=1e9;S.lvl=6;for(const c of ['prg','ber'])ACT.buildPop({city:c});
|
||||
for(const c in S.pops)S.pops[c].rgen=3;
|
||||
S.links=[{id:'fp1',a:'fra',b:'prg',kind:'wave',tier:2,km:409,mo:100},
|
||||
{id:'fp2',a:'fra',b:'prg',kind:'wave',tier:2,km:409,mo:100},
|
||||
{id:'fb',a:'fra',b:'ber',kind:'wave',tier:2,km:420,mo:100},
|
||||
{id:'pb',a:'prg',b:'ber',kind:'wave',tier:2,km:280,mo:100}];
|
||||
S.transit=[{id:'tp',city:'prg',net:'cog',tier:2},{id:'tb',city:'ber',net:'cog',tier:2}];
|
||||
S.scrubs=[{city:'fra',tier:1}];
|
||||
S.ev.ddos={id:'b',city:'ber',vec:'ack',gbps:50,start:0,until:7,entry:{k:'t',id:'tb'}};
|
||||
S.ev.ddosMore=[{id:'p',city:'prg',vec:'ack',gbps:50,start:0,until:7,entry:{k:'t',id:'tp'}}];compute()`);
|
||||
const sources = id => JSON.parse(ev(`JSON.stringify(Object.entries(R.ef[edgeKey(S.links.find(l=>l.id==='${id}'))].eg)
|
||||
.filter(([key])=>key.startsWith('scrub:')).map(([key,g])=>({city:R.egDesc[key].city,g})).sort((a,b)=>a.city.localeCompare(b.city)))`));
|
||||
assert.equal(ev('R.load.pb||0'), 0, 'Berlin does not feed the Prague link');
|
||||
assert.deepEqual(sources('fp1').map(x=>x.city), ['prg']);
|
||||
assert.deepEqual(sources('fb').map(x=>x.city), ['ber']);
|
||||
assert.ok(sources('fp1')[0].g>0 && sources('fb')[0].g>0);
|
||||
assert.ok(Math.abs(sources('fp1')[0].g-ev('R.load.fp1+R.load.fp2'))<1e-9, 'the grouped record covers both parallel links exactly');
|
||||
ev("selectLink('fp1');draw(0)");
|
||||
const row = [...dom.window.document.querySelectorAll('#panelBody .row')].find(x=>x.querySelector('.nm')?.textContent==='Attack hauled to scrubbing in Frankfurt');
|
||||
assert.ok(row);
|
||||
assert.match(row.querySelector('.meta').textContent, /^Prague · /);
|
||||
assert.equal(JSON.parse(row.querySelector('[data-act="goEgress"]').dataset.args).city, 'prg');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify([...UI.feed])')), ['prg'], 'the map highlights the same source as the inspected link');
|
||||
row.querySelector('[data-act="goEgress"]').click();
|
||||
assert.equal(ev('UI.sel.id'), 'prg', 'Open goes to the actual source city');
|
||||
// Swapping the attacks' order and adding an overlapping flood must not change the attribution.
|
||||
ev("S.ev.ddosMore.push(S.ev.ddos,{...S.ev.ddos,id:'overlap',gbps:20});S.ev.ddos=S.ev.ddosMore.shift();compute()");
|
||||
assert.deepEqual(sources('fp1').map(x=>x.city), ['prg']);
|
||||
assert.deepEqual(sources('fb').map(x=>x.city), ['ber']);
|
||||
// When Berlin's direct link fails, its haul really does join Prague's route.
|
||||
ev('S.links.find(l=>l.id==="fb").cut=S.day+1;compute()');
|
||||
assert.ok(ev('R.load.pb')>0);
|
||||
assert.deepEqual(sources('fp1').map(x=>x.city), ['ber','prg']);
|
||||
assert.deepEqual(sources('pb').map(x=>x.city), ['ber']);
|
||||
assert.ok(Math.abs(sources('fp1').reduce((n,x)=>n+x.g,0)-ev('R.load.fp1+R.load.fp2'))<1e-9, 'shared-path totals still equal the actual link load');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
function setupScrubLatency(ev) {
|
||||
ev(`ACT.start({});S.cash=1e9;S.lvl=6;for(const c of ['par','nyc','ams'])ACT.buildPop({city:c});
|
||||
for(const c in S.pops)S.pops[c].rgen=RG.findIndex(g=>g.fs===1);
|
||||
S.links=[{id:'pf',a:'par',b:'fra',kind:'wave',tier:3,km:620/1.3,mo:100},
|
||||
{id:'fn',a:'fra',b:'nyc',kind:'wave',tier:3,km:6000,mo:100},
|
||||
{id:'fa',a:'fra',b:'ams',kind:'wave',tier:3,km:200,mo:100}];
|
||||
S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:2}];
|
||||
S.scrubs=[{city:'fra',tier:0},{city:'par',tier:0}];
|
||||
S.ev.ddos={id:'par-flood',city:'par',vec:'dns',gbps:33.8,start:0,until:7,
|
||||
entry:{k:'edge',lab:''}};compute()`);
|
||||
}
|
||||
|
||||
test('each attack shows only the nearest scrubbing detour using precise one-way link latency', () => {
|
||||
const { ev, errors } = load();
|
||||
setupScrubLatency(ev);
|
||||
ev("for(const c in S.pops)S.pops[c].rgen=3;S.scrubs=[{city:'fra',tier:0},{city:'ams',tier:0}];S.ev.ddos.vec='ack';S.ev.ddos.gbps=230;compute()");
|
||||
assert.equal(ev('ddosReport(S.ev.ddos).sp.parts.length'), 2, 'capacity spills between centers');
|
||||
const card = ev('ddosOne(S.ev.ddos)');
|
||||
assert.equal((card.match(/Scrubbing traffic hauled over your backbone/g)||[]).length, 1);
|
||||
assert.match(card, /✓ Scrubbing traffic hauled over your backbone: Paris → Frankfurt \(\+3\.1 ms\)/);
|
||||
// An overlapping attack has its own victim and nearest center.
|
||||
ev("S.ev.ddosMore=[{id:'other',city:'ams',vec:'ack',gbps:10,start:0,until:7,entry:{k:'edge',lab:''}}];compute()");
|
||||
assert.doesNotMatch(ev('ddosOne(S.ev.ddosMore[0])'), /Scrubbing traffic hauled over your backbone/);
|
||||
assert.match(ev('ddosOne(S.ev.ddos)'), /Paris → Frankfurt \(\+3\.1 ms\)/);
|
||||
// Ignore a failed nearby center and use the live path to Amsterdam.
|
||||
ev("S.pops.fra.down=10;S.links.push({id:'pa',a:'par',b:'ams',kind:'wave',tier:3,km:2000,mo:100});compute()");
|
||||
assert.match(ev('ddosOne(S.ev.ddos)'), /Paris → Amsterdam \(\+13\.0 ms\)/);
|
||||
ev('S.ev.ddos.bh=true;compute()');
|
||||
assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/);
|
||||
ev('S.ev.ddos.bh=false;S.scrubMode="ondemand";compute()');
|
||||
assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a constrained remote haul leaves scrubbing capacity for the next overlapping flood', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc'])S.pops[c].rgen=3;S.links=[{id:'thin',a:'nyc',b:'fra',kind:'wave',tier:1,km:6000,mo:100}];S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={id:'far',city:'nyc',vec:'http',gbps:600,start:0,until:7};S.ev.ddosMore=[{id:'near',city:'fra',vec:'http',gbps:900,start:0,until:7}];compute()");
|
||||
const clean = JSON.parse(ev('JSON.stringify(R.ddos.map(m=>({id:m.attack.id,clean:m.sp?.parts.reduce((n,x)=>n+x.cleaned,0)||0,leak:m.leak})))'));
|
||||
assert.equal(clean.find(m=>m.id==='near').clean, 900);
|
||||
assert.ok(clean.find(m=>m.id==='far').clean <= 100);
|
||||
assert.ok(clean.reduce((n,m)=>n+m.clean,0) <= 1000);
|
||||
for (const m of clean) assert.equal(m.clean+m.leak, m.id==='near'?900:600);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('RackNet and TeamSpooked require signed gaming customers, bypass Flowspec, and stay within a third of the current size range', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=13;S.pops.fra.bb={d:150000};ACT.buyTransit({city:'fra',net:'cog',tier:2});compute()");
|
||||
assert.equal(ev("ddosVectors().includes('racknet')||ddosVectors().includes('teamspooked')"), false);
|
||||
ev("S.offers=[{type:'game'}]");
|
||||
assert.equal(ev("ddosVectors().includes('racknet')"), false, 'an unsigned offer does not introduce gaming attacks');
|
||||
ev("S.biz=[{type:'game',id:'gamer',name:'Gamer',city:'fra',bw:0,rate:0}];compute()");
|
||||
for (const vec of ['racknet','teamspooked']) {
|
||||
assert.equal(ev(`DDOS_VEC.${vec}.fs`), false);
|
||||
const sizeMax = ev('ddosSizeMax()/3');
|
||||
ev(`const old=Math.random;let n=0;Math.random=()=>n++===1?(ddosVectors().indexOf('${vec}')+0.5)/ddosVectors().length:0.999999;ddosAttack();Math.random=old`);
|
||||
assert.equal(ev('ddosAll().at(-1).vec'), vec);
|
||||
assert.ok(ev('ddosAll().at(-1).gbps') <= sizeMax);
|
||||
assert.ok(ev('ddosAll().at(-1).gbps') > sizeMax*(1-0.00002), 'the upper randomized quantile approaches the one-third limit, including rare spikes');
|
||||
}
|
||||
ev("S.biz[0].type='cgame'");
|
||||
assert.equal(ev("ddosVectors().includes('teamspooked')"), true, 'cloud gaming also attracts these vectors');
|
||||
ev('S.biz=[]');
|
||||
assert.equal(ev("ddosVectors().includes('teamspooked')"), false);
|
||||
assert.equal(ev('ddosAll().length'), 2, 'existing attacks finish naturally after the gaming customer leaves');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('gamers\' DDoS starts rise gradually from half an attack per week and never exceed a seven-per-week expected rate', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.rules=makeRules('bgp');S.day=50");
|
||||
const checks = JSON.parse(ev(`
|
||||
const oldAttack=ddosAttack,oldRandom=Math.random,out=[];
|
||||
try {
|
||||
for(const [level,games] of [[1,0],[13,0],[1,1],[13,1],[13,10],[13,1000]]){
|
||||
S.lvl=level;S.biz=Array.from({length:games},()=>({type:'game'}));
|
||||
let starts=0,draw=0;ddosAttack=()=>{starts++};Math.random=()=>((draw++)+0.5)/14000;
|
||||
for(let day=0;day<7000;day++)ddosTick();
|
||||
out.push({level,games,expected:ddosRate(),observed:starts/1000});
|
||||
}
|
||||
} finally {ddosAttack=oldAttack;Math.random=oldRandom;}
|
||||
JSON.stringify(out)
|
||||
`));
|
||||
for(const row of checks){
|
||||
if(row.games===0){assert.equal(row.observed,0,'without gamers attacks stay on the failure schedule');continue;}
|
||||
assert.ok(Math.abs(row.observed-row.expected)<=0.0011, JSON.stringify(row));
|
||||
assert.ok(row.expected>0.5&&row.expected<=7);
|
||||
}
|
||||
assert.ok(checks[3].expected>checks[2].expected, 'level increases gaming frequency');
|
||||
assert.ok(checks[4].expected>checks[3].expected, 'more gaming customers increase frequency');
|
||||
assert.ok(checks[3].expected<0.8, 'one gaming customer does not suddenly add several attacks per week, even at the last level');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('normal attack sizes match the one- and fifty-gamer targets while frequency rises gradually', () => {
|
||||
const { ev, errors } = load();
|
||||
ev('ACT.start({})');
|
||||
const samples = JSON.parse(ev(`
|
||||
const oldRandom=Math.random,out=[];
|
||||
try {
|
||||
for(const [level,demand] of [[1,0],[3,1850],[LEVELS.length,LV_REQ.at(-1).pk]]){
|
||||
const counts=[];
|
||||
for(const games of [0,1,2,5,10,20,50,100,1000]){
|
||||
S.lvl=level;S.biz=Array.from({length:games},(_,i)=>({id:'g'+i,type:i%2?'cgame':'game',city:'fra',bw:0,rate:0}));
|
||||
const vectors=ddosVectors();let sum=0;
|
||||
for(let i=0;i<vectors.length;i++)for(const [roll,weight] of [[0.49,0.98],[0.99,0.02]]){
|
||||
S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];R.demand=demand;
|
||||
let draw=0;Math.random=()=>draw++===1?(i+0.5)/vectors.length:roll;
|
||||
ddosAttack(false);sum+=weight*S.ev.ddos.gbps;
|
||||
}
|
||||
counts.push({games,mean:sum/vectors.length,rate:ddosRate()});
|
||||
}
|
||||
out.push({level,demand,counts});
|
||||
}
|
||||
} finally {Math.random=oldRandom;}
|
||||
JSON.stringify(out)
|
||||
`));
|
||||
for(const row of samples){
|
||||
const [plain,first]=row.counts,fifty=row.counts.find(c=>c.games===50),hundred=row.counts.find(c=>c.games===100),many=row.counts.at(-1);
|
||||
assert.ok(Math.abs(first.mean-plain.mean*3)<0.003, 'the first gamer triples the overall mean, allowing only bandwidth rounding: '+JSON.stringify(row));
|
||||
assert.ok(Math.abs(fifty.mean-plain.mean*8)<0.01, 'fifty gamers bring eightfold sizes, allowing only bandwidth rounding');
|
||||
assert.ok(hundred.mean>first.mean*3, 'growth continues across dozens of gaming customers');
|
||||
assert.ok(hundred.mean>plain.mean*10 && hundred.mean<plain.mean*11, 'a hundred gamers bring roughly tenfold sizes');
|
||||
assert.ok(many.mean<=plain.mean*12+0.01, 'high-exposure sizes approach the existing upper balance');
|
||||
assert.equal(plain.rate,0.5);
|
||||
assert.ok(first.rate<0.8);
|
||||
assert.ok(hundred.rate>6 && many.rate<=7);
|
||||
for(let i=1;i<row.counts.length;i++){
|
||||
assert.ok(row.counts[i].mean>row.counts[i-1].mean, 'each sampled count increases actual spawned attack sizes');
|
||||
assert.ok(row.counts[i].rate>row.counts[i-1].rate, 'each sampled count increases frequency');
|
||||
}
|
||||
}
|
||||
assert.ok(Math.abs(samples[0].counts[0].mean-1)<0.001, 'the minimum-demand baseline still permits small attacks');
|
||||
assert.ok(Math.abs(samples[1].counts[0].mean-740/13)<0.001, 'the 1.85 Tbps non-gaming example keeps its average');
|
||||
assert.ok(Math.abs(samples[2].counts[0].mean-samples[2].demand*4/3/10)<0.001);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('normal attack sizes cover a broad ordinary range and a two-percent large tail without raising the mean', () => {
|
||||
const { ev, errors } = load();
|
||||
ev('ACT.start({});S.lvl=3;S.biz=[];R.demand=1850');
|
||||
const distribution = JSON.parse(ev(`
|
||||
const oldRandom=Math.random,ordinary=[],large=[];let sum=0;
|
||||
try {
|
||||
for(let i=0;i<10000;i++){
|
||||
Math.random=()=>(i+0.5)/10000;
|
||||
const g=ddosSize('syn');sum+=g;(g>100?large:ordinary).push(g);
|
||||
}
|
||||
} finally {Math.random=oldRandom;}
|
||||
JSON.stringify({ordinary:{n:ordinary.length,min:Math.min(...ordinary),max:Math.max(...ordinary)},
|
||||
large:{n:large.length,min:Math.min(...large),max:Math.max(...large),near500:large.some(g=>g>=490&&g<=510)},mean:sum/10000})
|
||||
`));
|
||||
assert.equal(distribution.ordinary.n, 9800);
|
||||
assert.equal(distribution.large.n, 200);
|
||||
assert.ok(distribution.ordinary.min>=8.9 && distribution.ordinary.min<10);
|
||||
assert.ok(distribution.ordinary.max>85 && distribution.ordinary.max<=89.1);
|
||||
assert.ok(distribution.ordinary.max/distribution.ordinary.min>9.9);
|
||||
assert.ok(distribution.large.min>=356 && distribution.large.max<=535);
|
||||
assert.ok(distribution.large.near500, 'the example network can occasionally face a roughly 500 Gbps flood');
|
||||
assert.ok(Math.abs(distribution.mean-740/13)<0.001, 'the rare tail preserves the previous 56.923 Gbps average');
|
||||
// Verify that real spawns use both bands, not just the standalone sampler.
|
||||
for (const [roll,minimum,maximum] of [[0.49,8.9,89.1],[0.99,356,535]]) {
|
||||
ev(`S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];R.demand=1850;const old=Math.random;let n=0;Math.random=()=>{const i=n++;return i===1?(ddosVectors().indexOf('syn')+0.5)/ddosVectors().length:i===2?${roll}:0.5};try{ddosAttack()}finally{Math.random=old}`);
|
||||
assert.equal(ev('S.ev.ddos.vec'), 'syn');
|
||||
assert.ok(ev('S.ev.ddos.gbps')>=minimum && ev('S.ev.ddos.gbps')<=maximum);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('Flood Season mixes terabit monsters with ordinary floods, and all of it grows through the year and after', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.scn={id:'flood',rules:{ddos:true}};S.lvl=3;S.biz=[];R.cityDem={fra:100}");
|
||||
// One draw: below a third a monster (800 to 3,400G), above it an ordinary flood up to 90% of the city's traffic.
|
||||
for (const [day,expected] of [[0,[800,3399,2,91]],[365,[1600,6799,4,183]],[730,[2400,10199,6,275]]]) {
|
||||
ev(`S.day=${day}`);
|
||||
const actual = JSON.parse(ev("const old=Math.random;let sizes;try{sizes=[0,1/3-1e-9,1/3,0.999999].map(r=>{Math.random=()=>r;return ddosSize('syn','fra')})}finally{Math.random=old}JSON.stringify(sizes)"));
|
||||
assert.deepEqual(actual, expected, `day ${day}`);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the busier DDoS schedule needs gaming customers; otherwise attacks come with the other incidents', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e9;S.day=50;S.lvl=13;S.biz=[];S.nextFail=1e9;S.nextEvent=1e9");
|
||||
const ticks = () => ev("(()=>{const old=Math.random,oa=ddosAttack;let n=0;ddosAttack=()=>{n++};Math.random=()=>0;try{for(let i=0;i<30;i++)ddosTick();}finally{Math.random=old;ddosAttack=oa;}return n;})()");
|
||||
assert.equal(ticks(), 0, 'no spicy chaos, no gamers: no extra schedule');
|
||||
// DDoS stays one of the regular incidents instead: some roll of fireFailure() still starts one.
|
||||
assert.ok(ev("(()=>{const old=Math.random;try{for(let i=0;i<200;i++){const r=i/200;Math.random=()=>r;S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];fireFailure();if(ddosAll().length)return true;}return false;}finally{Math.random=old;}})()"), 'fireFailure can start an attack');
|
||||
ev("S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];S.inc=[]");
|
||||
ev("S.biz=[{type:'game',city:'fra',bw:5,rate:1,reqs:[]}]");
|
||||
assert.ok(ticks() > 0, 'gaming customers bring their own attacks');
|
||||
ev("S.biz=[];S.rules=makeRules('bgp')");
|
||||
assert.equal(ticks(), 0, 'spicy chaos alone has no daily schedule: it doubles the incident one');
|
||||
ev("S.rules=makeRules('freeze')");
|
||||
assert.equal(ticks(), 0, 'Change Freeze has no attacks on either schedule');
|
||||
ev("S.biz=[{type:'game',city:'fra',bw:5,rate:1,reqs:[]}]");
|
||||
assert.equal(ticks(), 0, 'not even with gamers');
|
||||
assert.ok(ev("(()=>{const old=Math.random;try{for(let i=0;i<200;i++){const r=i/200;Math.random=()=>r;S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];fireFailure();if(ddosAll().length)return false;}return true;}finally{Math.random=old;S.inc=[];}})()"), 'and fireFailure never rolls one');
|
||||
ev("S.rules=makeRules('oncall');S.biz=[{type:'game',city:'fra',bw:5,rate:1,reqs:[]}]");
|
||||
assert.ok(ev("(()=>{const old=Math.random;try{for(let i=0;i<200;i++){const r=i/200;Math.random=()=>r;S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];fireFailure();if(ddosAll().length)return false;}return true;}finally{Math.random=old;S.inc=[];}})()"), 'gamers\' attacks come from their own schedule only, never twice');
|
||||
ev("S.biz=[]");
|
||||
ev("S.rules=makeRules('oncall')");
|
||||
// Flood Season, not spicy: one flood at a time, 3 to 7 days apart, however old the scenario is.
|
||||
ev("ACT.startScn({id:'flood',sure:1});S.biz=[]");
|
||||
const gaps = JSON.parse(ev("(()=>{const o=[];for(const d of [0,1000])for(const r of [0,0.999]){S.day=d;const old=Math.random;Math.random=()=>r;o.push(floodGap());Math.random=old;}return JSON.stringify(o);})()"));
|
||||
assert.deepEqual(gaps, [3, 7, 3, 7]);
|
||||
ev("S.scn.nextDdos=S.day;ddosTick()");
|
||||
assert.equal(ev('ddosAll().length'), 1);
|
||||
ev("S.scn.nextDdos=S.day;ddosTick()");
|
||||
assert.equal(ev('ddosAll().length'), 1, 'the next flood waits for the last one to end');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
|
|||
396
tests/gameplay-rules.test.js
Normal file
396
tests/gameplay-rules.test.js
Normal file
|
|
@ -0,0 +1,396 @@
|
|||
// The game's design rules (.claude/skills/gameplay-rules/SKILL.md): one test per rule id, on the live data.
|
||||
// A rule may only be broken by an entry in EXCEPTIONS below, with its reason. Never delete a check to make it pass.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const path = require('node:path');
|
||||
const fs = require('node:fs');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// Every exception names what breaks the rule and why. One per line, sorted within each rule.
|
||||
const EXCEPTIONS = {
|
||||
// W2: countries with fewer than two consumer networks of their own, because real life has fewer.
|
||||
W2: {
|
||||
CU: 'Cuba has one state operator (ETECSA); Cubacel is its own mobile brand',
|
||||
DJ: 'Djibouti Telecom is the monopoly for homes and phones',
|
||||
MH: 'the Marshall Islands have one telco (NTA)',
|
||||
PN: 'Pitcairn has no network at all: land your own cable (#124)',
|
||||
SH: 'St Helena has one operator (Sure South Atlantic)',
|
||||
},
|
||||
// W3: cities nobody sells transit in.
|
||||
W3: {
|
||||
ivc: 'Invercargill waits for its AI campus; nobody sells transit there yet',
|
||||
pcn: 'Pitcairn: no cable, no network, land your own (#124)',
|
||||
prr: 'Prince Rupert is a remote town with no carrier in it',
|
||||
stg: 'Stuttgart is the Only Spätzle-IX scenario city: peering only, by design (#114)',
|
||||
},
|
||||
// N3: networks in no founding Tier 1's customer cone. Old saves need PNIs with the founding five for Tier 1,
|
||||
// so anyone outside their cones has to be peered with directly.
|
||||
N3: {
|
||||
abb: 'Australians buy only from Australian carriers (#148)',
|
||||
atl: 'transit-free in India',
|
||||
bcd: 'transit-free in Canada',
|
||||
blg: 'Australian, buys from Telstraya (#148)',
|
||||
btt: 'transit-free incumbent',
|
||||
cht: 'transit-free in Taiwan',
|
||||
clr: 'America Movil, transit-free across Latin America',
|
||||
cmb: 'China (#59): reached through the Chinese carriers',
|
||||
cmc: 'transit-free incumbent',
|
||||
cos: 'Greek incumbent, peers for its own reach',
|
||||
ctc: 'China (#59)',
|
||||
cun: 'China (#59)',
|
||||
cxc: 'buys from Spectre-um, which is transit-free',
|
||||
drz: 'a transit-free Tier 2',
|
||||
dtk: 'transit-free incumbent',
|
||||
etc: 'Cuba: buys from Sparkly Seabone, a Tier 1 only for games since 1.12',
|
||||
ets: 'transit-free in the Gulf',
|
||||
ftr: 'buys from Very-Zone, which is transit-free',
|
||||
inp: 'Australian, buys from Toilet Paper Group (#148)',
|
||||
jio: 'transit-free in India',
|
||||
kdi: 'transit-free in Japan',
|
||||
ktt: 'Korea: sender pays, peer with it yourself',
|
||||
lgu: 'Korea: sender pays',
|
||||
lnt: 'Australian (#148)',
|
||||
lpt: 'Australian (#148)',
|
||||
meo: 'Portuguese incumbent, peers for its own reach',
|
||||
mgf: 'Russia: buys from Rostelecomedy (#70)',
|
||||
npt: 'Australian (#148)',
|
||||
ert: 'Russia: buys from Rostelecomedy (#70)',
|
||||
opt: 'Australian, buys from SingTell (#148)',
|
||||
pnt: 'Australian (#148)',
|
||||
rtc: 'Russia (#70)',
|
||||
sgt: 'a transit-free Tier 2',
|
||||
skb: 'Korea: sender pays',
|
||||
spc: 'transit-free incumbent',
|
||||
stb: 'satellite: peers for its own reach',
|
||||
stc: 'transit-free in Saudi Arabia',
|
||||
teg: 'owns the land crossing; transit-free',
|
||||
tim: 'buys from Sparkly Seabone, a Tier 1 only for games since 1.12',
|
||||
tmt: 'buys from Sparkly Seabone, a Tier 1 only for games since 1.12',
|
||||
tmx: 'transit-free in Mexico',
|
||||
tmy: 'Malaysian incumbent, peers for its own reach',
|
||||
tng: 'a transit-free Tier 2',
|
||||
tpr: 'Australian (#148)',
|
||||
tsf: 'Indonesian incumbent, peers for its own reach',
|
||||
tsy: 'Australian, transit-free (#148)',
|
||||
ttk: 'transit-free in Turkey',
|
||||
ups: 'European cable group, peers for its own reach',
|
||||
vdp: 'a transit-free Tier 2',
|
||||
viv: 'transit-free in Brazil',
|
||||
vzn: 'transit-free incumbent',
|
||||
},
|
||||
// N7: an exchange port where the network has no PoP.
|
||||
N7: {
|
||||
'spl:hba': 'Speedyloop reaches Hobart’s exchange over its own backhaul but sells no transit there',
|
||||
},
|
||||
// M3: subsystems that annoy the player but read no rule.
|
||||
M3: {},
|
||||
};
|
||||
|
||||
// The real names the puns are based on. No network, cable, exchange, data center, router or optic may be called one.
|
||||
const REAL_NAMES = [
|
||||
// Tier 1s and carriers
|
||||
'AT&T', 'BICS', 'Cogent', 'GTT', 'Hurricane Electric', 'Level 3', 'Level3', 'Liquid', 'Liquid Intelligent Technologies', 'Lumen', 'NTT', 'Orange', 'PCCW', 'Seacom', 'Singtel', 'Sparkle', 'Tata', 'Tata Communications', 'Telia', 'Telxius', 'Vodafone', 'Zayo',
|
||||
// content and clouds
|
||||
'Akamai', 'Alibaba Cloud', 'Amazon', 'Amazon Web Services', 'AWS', 'Baidu', 'ByteDance', 'Cloudflare', 'Facebook', 'Fastly', 'Google', 'Mercado Libre', 'Meta', 'Microsoft', 'Netflix', 'Tencent', 'TikTok', 'VK', 'VKontakte', 'Yandex',
|
||||
// eyeballs and incumbents
|
||||
'A1', 'A1 Telekom Austria', 'AIS', 'Airtel', 'Algérie Télécom', 'Altibox', 'Altice', 'America Movil', 'Angola Cables', 'Antel', 'ASTCA', 'Aussie Broadband', 'Bell', 'Bell Canada', 'Belong', 'Bemobile', 'Brisanet', 'BT', 'BTC', 'Cable & Wireless', 'Cable Bahamas', "CAN'L", 'Canal+', 'CANTV', 'CelcomDigi', 'China Mobile', 'China Telecom', 'China Unicom', 'Chunghwa Telecom', 'Citymesh', 'Claro', 'Comcast', 'Cosmote', 'Cox', 'CV Telecom', 'Deutsche Telekom', 'Dhiraagu', 'Dialog', 'Digi', 'Digicel', 'Djezzy', 'Djibouti Telecom', 'DNA', 'Docomo', 'Docomo Pacific', 'Dodo', 'du', 'Eastlink', 'Elisa', 'Emtel', 'Entel', 'ER-Telecom', 'Etisalat', 'ETECSA', 'Ethio Telecom', 'Exetel', 'Far EasTone', 'Fastweb', 'FINTEL', 'Flow', 'Free', 'Frontier', 'GCI', 'Globe', 'Google Fiber', 'Grameenphone', 'GSL Networks', 'GTA', 'Hawaiian Telcom', 'HKBN', 'HKT', 'iiNet', 'Jazz', 'Jio', 'KDDI', 'KPN', 'KT', 'Kyivstar', 'Launtel', 'Leaptel', 'LG U+', 'Liberty Latin America', 'lifecell', 'LMT', 'Magyar Telekom', 'Maroc Telecom', 'Mascom', 'Mauritius Telecom', 'MegaFon', 'MEO', 'Mobily', 'Movicel', 'Movistar', 'Movitel', 'MTC', 'MTN', 'mts', 'Neptune', 'Netvigator', 'Norlys', 'NOS', 'Nova', 'NTA', 'NTT Docomo', 'Oi', 'Omantel', 'One Communications', 'One NZ', 'Ooredoo', 'OPT', 'Optimum', 'Optus', 'Palau Mobile', 'Paradise Mobile', 'Pentanet', 'PLDT', 'PNCC', 'POST', 'Proximus', 'PTCL', 'Reliance Jio', 'Robi', 'Rogers', 'Rostelecom', 'Safaricom', 'SFR', 'Síminn', 'SK Broadband', 'Sky', 'SLT', 'Sonic', 'Spark', 'Spectrum', 'Spintel', 'Starlink', 'StarHub', 'STC', 'Superloop', 'Sure', 'Swisscom', 'T-Mobile', 'Tango', 'TCC', 'TDC', 'Tele2', 'Telecel', 'Telecom Argentina', 'Telecom Egypt', 'Telecom Fiji', 'Telecom Namibia', 'Telekom Malaysia', 'Telekom Srbija', 'Telenet', 'Telenor', 'Telikom PNG', 'Telkomsel', 'Telma', 'Telmex', 'TelOne', 'Telstra', 'Telus', 'Tet', 'TIM', 'Tigo', 'TPG', 'True', 'True Move', 'TSTT', 'Turk Telekom', 'Unitel', 'UPC', 'Verizon', 'Viettel', 'Vini', 'Virgin Media', 'Vivacom', 'Vivo', 'VNPT', 'Vocus', 'Yas', 'Yettel', 'YouSee', 'Zeop',
|
||||
// exchanges and data centers
|
||||
'AMS-IX', 'Any2', 'BCIX', 'CoreSite', 'DE-CIX', 'Digital Realty', 'Equinix', 'France-IX', 'Interxion', 'IX.br', 'JPIX', 'LINX', 'NAPAfrica', 'NetIX', 'NIX', 'NL-ix', 'SIX', 'Telehouse',
|
||||
// cables
|
||||
'2Africa', 'Amitié', 'Dunant', 'EllaLink', 'Equiano', 'Grace Hopper', 'Hibernia Express', 'Jupiter', 'MAREA', 'PEACE', 'SEA-ME-WE 6',
|
||||
// vendors
|
||||
'Arista', 'Brocade', 'Ciena', 'Cisco', 'Extreme Networks', 'Huawei', 'Infinera', 'Juniper', 'MikroTik', 'Nokia',
|
||||
];
|
||||
|
||||
const { ev, errors } = load();
|
||||
ev('ACT.start({})');
|
||||
const J = (s) => JSON.parse(ev(`JSON.stringify(${s})`));
|
||||
const country = (cc) => { try { return new Intl.DisplayNames(['en'], { type: 'region' }).of(cc); } catch (e) { return cc; } };
|
||||
const fail = (id, bad, fix) => assert.deepEqual(bad, [], `${id}: ${bad.join('; ')}. ${fix}`);
|
||||
const ex = (id, k) => Object.prototype.hasOwnProperty.call(EXCEPTIONS[id] || {}, k);
|
||||
|
||||
// ---------- World ----------
|
||||
|
||||
test('W1: every city has a country code, a region and real coordinates', () => {
|
||||
const bad = J(`CITIES.filter(c=>!/^[A-Z]{2}$/.test(c.cc||'')||!['AM','SA','EU','AS','OC','AF'].includes(c.reg)||!(Math.abs(c.lat)<=90&&Math.abs(c.lon)<=180&&CITY_LL[c.id])||!c.land).map(c=>c.id+' ('+c.name+')')`);
|
||||
fail('W1', bad, 'give it cc (ISO 3166-1 alpha-2; territories have their own), reg, land and an entry in CITY_LL');
|
||||
});
|
||||
|
||||
test('W2: every country on the map has at least two consumer networks of its own', () => {
|
||||
// "Own": the network names the country in its home markets (cc) and has a PoP there. Consumer networks are the
|
||||
// eyeballs, and the Tier 2 incumbents that sell to homes and phones in their home markets.
|
||||
const rows = J(`(()=>{const cs={};for(const c of CITIES)if(!c.off)(cs[c.cc]=cs[c.cc]||[]).push(c.id);
|
||||
return Object.keys(cs).sort().map(cc=>[cc,NETS.filter(n=>(n.type==='eye'||n.type==='t2')&&[].concat(n.cc||[]).includes(cc)&&n.pops.some(p=>CITY[p].cc===cc)).map(n=>n.name)]);})()`);
|
||||
const bad = rows.filter(([cc, own]) => own.length < 2 && !ex('W2', cc))
|
||||
.map(([cc, own]) => `${country(cc)} (${cc}) has ${own.length} own eyeball network${own.length === 1 ? '' : 's'}${own.length ? ': ' + own.join(', ') : ''}`);
|
||||
fail('W2', bad, 'add a real operator of that country (src/game/30-networks/32-homegrown-eyeballs.js) or list it in EXCEPTIONS with a reason');
|
||||
const stale = Object.keys(EXCEPTIONS.W2).filter((cc) => (rows.find((r) => r[0] === cc) || [cc, [1, 2]])[1].length >= 2);
|
||||
assert.deepEqual(stale, [], 'W2: these exceptions are no longer needed; remove them');
|
||||
// a network's home markets are places it really is
|
||||
const homeless = J(`NETS.filter(n=>n.cc).flatMap(n=>[].concat(n.cc).filter(cc=>!n.pops.some(p=>CITY[p].cc===cc)).map(cc=>n.name+' has no PoP in '+cc))`);
|
||||
fail('W2', homeless, 'a home market (cc) needs a PoP in that country');
|
||||
});
|
||||
|
||||
test('W3: every city can buy transit from someone, or is a documented exception', () => {
|
||||
const bad = J(`CITIES.filter(c=>!c.off&&!NETS.some(n=>sellsAt(n,c.id))).map(c=>c.id)`).filter((c) => !ex('W3', c));
|
||||
fail('W3', bad, 'give a carrier a PoP there (with a price) or list the city in EXCEPTIONS with a reason');
|
||||
});
|
||||
|
||||
test('W4: cables are consistent: real cities, two distinct ends, a length and unique ids', () => {
|
||||
const bad = J(`CABLE_PAIRS.filter(p=>!CITY[p.a]||!CITY[p.b]||p.a===p.b||!(p.km>0)||!CAB[p.cid]).map(p=>p.cid+':'+p.a+'-'+p.b)`);
|
||||
fail('W4', bad, 'fix the cable pair in src/game/20-world/60-cables.js');
|
||||
const ids = J('CABLES.map(c=>c.id)');
|
||||
assert.equal(new Set(ids).size, ids.length, 'W4: cable ids are unique');
|
||||
fail('W4', J("CABLES.filter(c=>!c.name||!c.pairs||!c.pairs.length).map(c=>c.id)"), 'every cable has a name and at least one landing pair');
|
||||
});
|
||||
|
||||
test('W5: every island city can be reached: it shares its land, has a cable, or a beach to land one', () => {
|
||||
const bad = J(`CITIES.filter(c=>!c.off&&!CITIES.some(o=>o!==c&&!o.off&&(o.land===c.land||o.land2===c.land||c.land2===o.land))&&!landing(c.id)).map(c=>c.id)`);
|
||||
fail('W5', bad, 'land a cable there or give it beach:true');
|
||||
});
|
||||
|
||||
// ---------- Networks ----------
|
||||
|
||||
test('N1: network ids and ASNs are unique, ASNs are valid', () => {
|
||||
const ids = J('NETS.map(n=>n.id)'), asns = J('NETS.map(n=>n.asn)');
|
||||
fail('N1', ids.filter((x, i) => ids.indexOf(x) !== i), 'network ids must be unique');
|
||||
fail('N1', asns.filter((x, i) => asns.indexOf(x) !== i).map(String), 'ASNs must be unique');
|
||||
fail('N1', J("NETS.filter(n=>!Number.isInteger(n.asn)||n.asn<1||n.asn>4294967294||n.asn>=64512&&n.asn<=65534).map(n=>n.id)"), 'use the real, public ASN');
|
||||
});
|
||||
|
||||
test('N2: names are puns: no network, cable, exchange, data center, router or optic carries a real name', () => {
|
||||
const norm = (s) => String(s).toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[’`]/g, "'").replace(/\s+/g, ' ').trim();
|
||||
const real = new Set(REAL_NAMES.map(norm));
|
||||
const names = J(`[...NETS.map(n=>['network',n.name]),...CABLES.map(c=>['cable',c.name]),...XIX.map(x=>['exchange',x.name]),
|
||||
...CITIES.flatMap(c=>[['exchange',c.ix],['data center',c.dc],['data center',c.dc2]]),...RG.map(r=>['router',r.n]),...Object.values(OPT).map(o=>['optic',o.n]),...Object.values(SEAT_ROUTES).flat().map(r=>['cable',r[2]])].filter(x=>x[1])`);
|
||||
fail('N2', names.filter(([, n]) => real.has(norm(n))).map(([k, n]) => `${k} “${n}” is a real name`), 'find a pun');
|
||||
fail('N2', names.filter(([, n]) => /-ish\b/i.test(n)).map(([k, n]) => `${k} “${n}”`), 'no lazy -ish names: find a real pun, or keep the plain word');
|
||||
});
|
||||
|
||||
test('N3: every network sits in a founding Tier 1’s customer cone, or is a documented island', () => {
|
||||
// The founding five (t1Need() of the oldest saves): every save can reach a network in their cones by peering with them.
|
||||
const out = J(`NETS.filter(n=>n.type!=='t1'&&n.type!=='cdn'&&!['lvl','ntt','tly','cog','tat'].some(t=>CONE_S[t].has(n.id))).map(n=>n.id)`);
|
||||
fail('N3', out.filter((id) => !ex('N3', id)).map((id) => `${id} (${ev(`NET.${id}.name`)})`), 'give it a realistic upstream (up) in a founding Tier 1’s cone, or list it in EXCEPTIONS with a reason');
|
||||
fail('N3', Object.keys(EXCEPTIONS.N3).filter((id) => !out.includes(id)), 'these exceptions are no longer needed; remove them');
|
||||
fail('N3', J("NETS.filter(n=>(n.up||[]).some(u=>!NET[u]||NET[u].type==='cdn'||u===n.id)).map(n=>n.id)"), 'an upstream is another network that exists and sells transit, never content');
|
||||
});
|
||||
|
||||
test('N4: no upstream cycles', () => {
|
||||
const bad = J(`(()=>{const o=[];for(const n of NETS){const seen=new Set(),q=(n.up||[]).slice();while(q.length){const u=q.pop();if(u===n.id){o.push(n.id);break;}if(seen.has(u))continue;seen.add(u);q.push(...((NET[u]||{}).up||[]));}}return o;})()`);
|
||||
fail('N4', bad, 'a network cannot buy transit from its own customers');
|
||||
});
|
||||
|
||||
test('N5: traffic shares are sane', () => {
|
||||
fail('N5', J("NETS.filter(n=>!(n.share>0&&n.share<0.2)).map(n=>n.id)"), 'every share is positive and below 20%');
|
||||
for (const t of ['NSH', 'NSH_CN', 'NSH_RU', 'NSH_KRX']) {
|
||||
assert.ok(Math.abs(ev(`Object.values(${t}).reduce((a,b)=>a+b,0)`) - 1) < 1e-9, `N5: ${t} sums to 1`);
|
||||
fail('N5', J(`Object.entries(${t}).filter(([k,v])=>!NET[k]||!(v>=0)).map(([k])=>k)`), `${t} only holds real networks, never negative`);
|
||||
}
|
||||
// the content giants carry the traffic, eyeballs mostly ask for it
|
||||
assert.ok(ev("NETS.filter(n=>n.type==='cdn').reduce((a,n)=>a+NSH[n.id],0)") > 0.3, 'N5: content is at least 30% of traffic');
|
||||
});
|
||||
|
||||
test('N6: every network has a type, a peering policy and a translated blurb', () => {
|
||||
fail('N6', J(`NETS.filter(n=>!['t1','t2','cdn','eye'].includes(n.type)||!['open','selective','restrictive','paid'].includes(n.pol)||!n.blurb||!n.col).map(n=>n.id)`), 'set type, pol, col and blurb:tr(...)');
|
||||
fail('N6', J("NETS.filter(n=>n.pol==='selective'&&!(n.minIx>=1&&n.minPni>=1)).map(n=>n.id)"), 'selective networks state minIx and minPni');
|
||||
fail('N6', J("NETS.filter(n=>n.type==='t1'||n.type==='t2'?!(n.price>0):false).map(n=>n.id)"), 'carriers have a transit price');
|
||||
});
|
||||
|
||||
test('N7: presence is real: PoPs are cities, exchange ports only where the network is', () => {
|
||||
fail('N7', J("NETS.filter(n=>!n.pops.length||n.pops.some(c=>!CITY[c])||new Set(n.pops).size!==n.pops.length).map(n=>n.id)"), 'PoPs are real, distinct city ids');
|
||||
const bad = J(`NETS.filter(n=>Array.isArray(n.ix)).flatMap(n=>n.ix.filter(c=>!XIXM[c]&&(!CITY[c]||!CITY[c].ix||!n.pops.includes(c))).map(c=>n.id+':'+c))`).filter((k) => !ex('N7', k));
|
||||
fail('N7', bad, 'an exchange port needs an exchange in that city and a PoP there');
|
||||
});
|
||||
|
||||
// ---------- Modes and rules ----------
|
||||
|
||||
test('M1: On-call is the classic game: the default rules, and what old saves load as', () => {
|
||||
assert.deepEqual(J("(({preset,mods,...r})=>r)(makeRules('oncall'))"), J("(({mods,...r})=>r)(RULE_DEF)"), 'M1: On-call is RULE_DEF');
|
||||
assert.equal(ev("(()=>{const o=S.rules;delete S.rules;const p=rulePreset();S.rules=o;return p;})()"), 'oncall', 'M1: no rules means On-call');
|
||||
// the seeded On-call games are the rest of the suite (tests/game.test.js, tests/rules.test.js); they must stay green
|
||||
});
|
||||
|
||||
test('M2: presets are ordered: Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler', () => {
|
||||
const P = J('PRESETS'), C = J('CHAOS'), lead = { quick: 0, real: 1 };
|
||||
assert.ok(C[P.freeze.chaos].m <= C[P.oncall.chaos].m && C[P.oncall.chaos].m <= C[P.bgp.chaos].m, 'M2: chaos');
|
||||
assert.ok(lead[P.freeze.lead] <= lead[P.oncall.lead] && lead[P.oncall.lead] <= lead[P.bgp.lead], 'M2: lead times');
|
||||
assert.ok(!P.freeze.market || P.oncall.market, 'M2: market');
|
||||
assert.ok(P.bgp.market && P.bgp.money === 'normal' && P.bgp.gates === 'ladder', 'M2: BGP keeps every hardship');
|
||||
// seeded: the same network for a year under each preset
|
||||
const n = {};
|
||||
for (const p of ['freeze', 'oncall', 'bgp']) {
|
||||
const g = load();
|
||||
g.ev(`beginGame('Order','fra',${JSON.stringify({ mode: 'normal', preset: p })});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});__reseed(4242);for(let i=0;i<360;i++)dayTick()`);
|
||||
n[p] = g.ev('S.inc.length+S.stats.survived+(S.stats.incidents||0)');
|
||||
assert.deepEqual(g.errors, []);
|
||||
}
|
||||
assert.ok(n.freeze <= n.oncall && n.oncall <= n.bgp, `M2: incidents in a year: freeze ${n.freeze}, on-call ${n.oncall}, bgp ${n.bgp}`);
|
||||
});
|
||||
|
||||
test('M3: every subsystem that can annoy the player reads a rule', () => {
|
||||
// [function, what it must read]
|
||||
const reads = [['dayTick', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'],
|
||||
['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'],
|
||||
['dfBuildDays', 'leadDays'], ['dayTick', "rule('clock')"], ['snub', "rule('market')"]];
|
||||
fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${JSON.stringify(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)');
|
||||
// and in play: no chaos and no market means a quiet year
|
||||
const g = load();
|
||||
g.ev("beginGame('Quiet','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall',{chaos:'none',market:false});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});for(let i=0;i<360;i++)dayTick()");
|
||||
assert.equal(g.ev('S.inc.length+(S.stats.incidents||0)'), 0, 'M3: nothing breaks without chaos');
|
||||
assert.equal(g.ev("hwMul('rt')"), 1, 'M3: no hardware inflation without the market');
|
||||
assert.equal(g.ev("CITIES.slice(0,40).some(c=>soldOut('fra',c.id,1))"), false, 'M3: no sold-out routes without the market');
|
||||
assert.deepEqual(g.errors, []);
|
||||
assert.ok(Object.keys(EXCEPTIONS.M3).every((f) => ev(`typeof ${f}==='function'`)), 'M3: exceptions name real functions');
|
||||
});
|
||||
|
||||
test('M4: scenarios and the weekly challenge always run On-call', () => {
|
||||
const g = load();
|
||||
const bad = [];
|
||||
for (const id of g.ev('JSON.stringify(SCN.map(x=>x.id))') && JSON.parse(g.ev('JSON.stringify(SCN.map(x=>x.id))'))) {
|
||||
g.ev(`beginGame('S','${id}'==='weekly'?'fra':SCN.find(x=>x.id==='${id}').city,{mode:'normal',preset:'bgp',rules:{chaos:'spicy'},scn:SCN.find(x=>x.id==='${id}')});if(UI.pendGame)ACT.pitchSkip()`);
|
||||
if (g.ev('S.rules.preset') !== 'oncall' || g.ev("rule('chaos')") !== 'normal') bad.push(id);
|
||||
}
|
||||
g.ev("ACT.startWeekly({sure:1});if(UI.pendGame)ACT.pitchSkip()");
|
||||
if (g.ev('S.scn&&S.scn.id') !== 'weekly' || g.ev('S.rules.preset') !== 'oncall') bad.push('weekly');
|
||||
fail('M4', bad, 'beginGame() must give scenarios On-call plus their own S.scn.rules');
|
||||
assert.deepEqual(g.errors, []);
|
||||
});
|
||||
|
||||
test('M5: Sandbox has no locked feature', () => {
|
||||
const g = load();
|
||||
g.ev("beginGame('Box','fra',{mode:'sandbox'});if(UI.pendGame)ACT.pitchSkip()");
|
||||
assert.equal(g.ev('gatesOpen()'), true, 'M5: gates open');
|
||||
assert.equal(g.ev('lvl()'), g.ev('LEVELS.length'), 'M5: every level unlocked');
|
||||
assert.equal(g.ev('cabOpen()'), true, 'M5: own subsea cables');
|
||||
assert.equal(g.ev("rule('money')"), 'infinite', 'M5: money');
|
||||
assert.deepEqual(g.errors, []);
|
||||
});
|
||||
|
||||
// ---------- Content ----------
|
||||
|
||||
test('C1: every scenario has a goal its card checks, and none is won on day 0', () => {
|
||||
const g = load();
|
||||
const ids = JSON.parse(g.ev('JSON.stringify(SCN.map(x=>x.id))'));
|
||||
assert.equal(new Set(ids).size, ids.length, 'C1: scenario ids are unique');
|
||||
const bad = [];
|
||||
for (const id of ids) {
|
||||
g.ev(`ACT.startScn({id:'${id}',sure:1});if(UI.pendGame)ACT.pitchSkip()`);
|
||||
const def = `SCN.find(x=>x.id==='${id}')`;
|
||||
if (!g.ev(`!!(${def}.n&&${def}.d&&${def}.goal&&typeof ${def}.ok==='function'&&${def}.days>0&&CITY[${def}.city])`)) bad.push(id + ': incomplete definition');
|
||||
if (g.ev(`(()=>{try{return !!${def}.ok();}catch(e){return false;}})()`)) bad.push(id + ': won on day 0');
|
||||
if (!g.ev(`typeof SCN_PROG['${id}']==='function'&&scnProg().items.length>0`)) bad.push(id + ': no progress card (SCN_PROG)');
|
||||
}
|
||||
// The published weekly scenarios too: each committed week starts, has its goal type's card, and needs play.
|
||||
const wdir = path.join(__dirname, '..', 'site', 'scenarios', 'weekly');
|
||||
for (const f of fs.readdirSync(wdir).filter((x) => /^\d{4}-W\d{2}\.json$/.test(x))) {
|
||||
const j = fs.readFileSync(path.join(wdir, f), 'utf8'), id = 'weekly ' + f.slice(0, -5);
|
||||
if (!g.ev(`wsBegin(${j},'S')`)) { bad.push(id + ': the game rejects it'); continue; }
|
||||
g.ev('if(UI.pendGame)ACT.pitchSkip();closeModal();compute()');
|
||||
if (g.ev('wsOk()')) bad.push(id + ': won on day 0');
|
||||
if (!g.ev('scnProg().items.length>0&&!!scnName()&&!!wsGoalTxt(S.scn.wk)')) bad.push(id + ': no progress card or goal');
|
||||
if (g.ev('S.rules.preset') !== 'oncall') bad.push(id + ': not On-call (M4)');
|
||||
}
|
||||
fail('C1', bad, 'give it n, d, goal, ok(), days, a city and a SCN_PROG entry; its goal must need play');
|
||||
assert.deepEqual(g.errors, []);
|
||||
});
|
||||
|
||||
test('C2: every puzzle has a 1-star and a 3-star reference solution (tests/puzzles.test.js)', () => {
|
||||
const src = fs.readFileSync(path.join(__dirname, 'puzzles.test.js'), 'utf8');
|
||||
const refs = [...src.matchAll(/^\s{2}([a-z0-9]+): \{ one: .*three: /gm)].map((m) => m[1]);
|
||||
fail('C2', J('PZ.map(p=>p.id)').filter((id) => !refs.includes(id)), 'add its reference solutions to REF in tests/puzzles.test.js (that suite builds and scores them)');
|
||||
});
|
||||
|
||||
test('C3: every player-facing string is translated in every language', () => {
|
||||
const out = execFileSync(process.execPath, [path.join(__dirname, '..', 'scripts', 'i18n-check.js')], { encoding: 'utf8' });
|
||||
assert.match(out, /en\.js: \d+ labels, 0 problems/, 'C3: ' + out);
|
||||
const langs = out.split('\n').filter((l) => /^[a-z]{2}\.js: \d+ missing/.test(l));
|
||||
assert.ok(langs.length >= 5, 'C3: every language is checked');
|
||||
fail('C3', langs.filter((l) => !/0 missing, 0 unused, 0 broken/.test(l)), 'run node scripts/i18n-add.js (add-strings skill)');
|
||||
});
|
||||
|
||||
// ---------- Fun and fairness ----------
|
||||
|
||||
test('F1: new players get a gentle start: nothing breaks for 45 days, no sold-out routes for 90, no hardware inflation for 180', () => {
|
||||
const g = load();
|
||||
g.ev("beginGame('New','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip()");
|
||||
assert.ok(g.ev('S.nextFail') >= 45 && g.ev('S.nextEvent') >= 40, 'F1: first outage after day 45, first event after day 40');
|
||||
// the first events are only good news or harmless (a viral hit, a price change, a grant)
|
||||
const opts = JSON.parse(g.ev(`(()=>{let o=null;const f=eval('('+fireEvent.toString().replace('const e=pick(opts);','o=opts.slice();return;')+')');S.day=45;f();return JSON.stringify(o);})()`));
|
||||
fail('F1', opts.filter((e) => !['viral', 'price', 'grant'].includes(e)), 'no bad events before day 50');
|
||||
assert.equal(g.ev("(()=>{for(let d=0;d<90;d++){S.day=d;if(CITIES.some(c=>soldOut('fra',c.id,1)))return true;}return false;})()"), false, 'F1: nothing sold out in the first 90 days');
|
||||
assert.equal(g.ev("(()=>{S.day=180;return hwMul('rt');})()"), 1, 'F1: hardware prices hold for 180 days');
|
||||
// customers get 15 days before a bad day costs them mood
|
||||
g.ev("S.day=10;S.biz=[{id:'b1',city:'fra',city2:null,reqs:[],name:'X',type:'host',bw:5,rate:100,mood:80,since:5}];compute();dayTick()");
|
||||
assert.ok(g.ev("(S.biz[0]||{mood:0}).mood") >= 80, 'F1: no mood loss in a customer’s first 15 days');
|
||||
assert.deepEqual(g.errors, []);
|
||||
});
|
||||
|
||||
test('F2: a simple build in a start city makes money within three months on On-call', () => {
|
||||
// Reference build: launch broadband, the cheapest 100G transit in town, and a port with a route server where there is an exchange.
|
||||
const bad = [];
|
||||
for (const city of ['fra', 'nyc', 'sin', 'jnb']) {
|
||||
const g = load();
|
||||
g.ev(`beginGame('Ref','${city}',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip()`);
|
||||
g.ev(`(()=>{const c='${city}',n=NETS.filter(n=>sellsAt(n,c)).sort((a,b)=>a.price*netMult(a,c)-b.price*netMult(b,c))[0];
|
||||
ACT.launchBB({city:c});ACT.buyTransit({city:c,net:n.id,tier:1});if(ixName(c)){ACT.buyIx({city:c,tier:1,signed:true});ACT.rs({city:c});}})()`);
|
||||
let month = 0;
|
||||
for (let m = 1; m <= 3 && !month; m++) { g.ev('for(let i=0;i<30;i++)dayTick()'); if (g.ev('R.revMo-R.costMo') > 0) month = m; }
|
||||
if (!month || g.ev('S.lost')) bad.push(`${city}: still losing money after 3 months (${Math.round(g.ev('R.revMo-R.costMo'))}/mo)`);
|
||||
assert.deepEqual(g.errors, []);
|
||||
}
|
||||
fail('F2', bad, 'a balance change made the start too hard; fix the balance, or argue for a new N in the gameplay-rules skill');
|
||||
});
|
||||
|
||||
test('F3: a specialist path only brings customers you can already serve', () => {
|
||||
const g = load();
|
||||
g.ev("ACT.start({});S.cash=1e9;S.lvl=1;for(const c of ['nyc','chi','ash'])S.pops[c]=S.pops[c]||{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}");
|
||||
g.ev("S.links.push({id:'w',a:'nyc',b:'chi',kind:'wave',tier:2,km:kmBetween('nyc','chi'),cut:0,mo:0},{id:'d',a:'chi',b:'ash',kind:'df',own:true,sys:'roadm',ch:['zr4','zr4','zr4','zr4'],km:kmBetween('chi','ash'),sub:false,cable:null,mo:0,trench:'d',cut:0,day:0,ready:0,spares:false},{id:'e',a:'nyc',b:'ash',kind:'df',own:true,sys:'roadm',ch:['zr4'],km:kmBetween('nyc','ash'),sub:false,cable:null,mo:0,trench:'e',cut:0,day:0,ready:0,spares:false});compute()");
|
||||
const Jg = (x) => JSON.parse(g.ev(`JSON.stringify(${x})`));
|
||||
const sp = Jg('spots()');
|
||||
assert.ok(sp.length > 0, 'F3: the reference network is spotted');
|
||||
const bad = [];
|
||||
for (const s of sp) {
|
||||
const T = Jg(`BIZ_T.${s.t}`);
|
||||
if (!(T.lv > 1)) bad.push(`${s.t} needs no spotting at level 1`);
|
||||
if (![s.a, s.b].filter(Boolean).every((c) => g.ev(`!!S.pops['${c}']`))) bad.push(`${s.t} names a city without a POP`);
|
||||
if (s.k === 'lat' && !(g.ev(`bestLat('${s.a}','${s.b}')<=latMaxOf('${s.a}','${s.b}')`))) bad.push(`${s.t} ${s.a}–${s.b} is too slow`);
|
||||
if (s.k === 'df' && !(s.n >= T.opts[0] * 0.75)) bad.push(`${s.t} ${s.a}–${s.b} asks for far more than the fiber carries`);
|
||||
}
|
||||
fail('F3', bad, 'spots0() must only name what the network can serve, or nearly');
|
||||
assert.deepEqual(g.errors, []);
|
||||
});
|
||||
|
||||
test('F4: the chaos monkey only visits On-call and BGP at 3 a.m., late, for 120 to 240 days, instead of the ordinary failures', () => {
|
||||
for (const preset of ['freeze', 'oncall', 'bgp']) {
|
||||
const g = load();
|
||||
g.ev(`beginGame('Monkey','fra',{mode:'normal',preset:'${preset}'});if(UI.pendGame)ACT.pitchSkip()`);
|
||||
g.ev("S.cash=1e9;S.lvl=4;for(const c of ['ams','lon','par'])ACT.buildPop({city:c});for(const [a,b] of [['fra','ams'],['ams','lon'],['lon','par'],['par','fra']]){UI.pending={a,b};ACT.buildLink({tier:1});}closeModal()");
|
||||
g.ev('for(let i=0;i<2;i++)dayTick()');
|
||||
if (preset === 'freeze') { assert.equal(g.ev('mkElig()'), false, 'F4: never in Change Freeze'); continue; }
|
||||
assert.ok(g.ev('S.monkey.next') >= 180, 'F4: not before day 180');
|
||||
g.ev('S.monkey.next=S.day;dayTick();S.nextFail=S.day');
|
||||
const len = g.ev('S.monkey.until-S.monkey.start');
|
||||
assert.ok(len >= 120 && len <= 240, `F4: a visit of ${len} days`);
|
||||
g.ev('for(let i=0;i<40;i++)dayTick()');
|
||||
assert.ok(g.ev('S.nextFail') <= g.ev('S.day'), 'F4: no ordinary failure fired during the visit');
|
||||
assert.ok(g.ev("S.inc.filter(i=>i.type==='cut').every(i=>i.until-i.start<=(rule('chaos')==='spicy'?11:7))"), 'F4: snips heal within a week (spicy stretches by half)');
|
||||
assert.deepEqual(g.errors, []);
|
||||
}
|
||||
const g = load();
|
||||
g.ev("beginGame('Monkey','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip();S.mode='sandbox'");
|
||||
assert.equal(g.ev('mkElig()'), false, 'F4: never in Sandbox');
|
||||
});
|
||||
|
||||
test('F5: rented capacity never outgrows the route\'s market (#203)', () => {
|
||||
const g = load();
|
||||
g.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;S.biz=[];S.offers=[];for(const c of ['jed','gdx'])ACT.buildPop({city:c})");
|
||||
g.ev("S.links.push({id:'f',a:'jed',b:'gdx',kind:'df',own:true,sys:'roadm',ch:[],km:9089,ready:0,day:0,cut:0,mo:1,trench:'own:f',pairs:1});compute();__reseed(5);ACT.listFiber({id:'f',w:120,p:1})");
|
||||
g.ev('for(let d=0;d<1500;d++){brTick();if(d%7===0)spawnOffer();}for(const o of S.offers.filter(o=>o.link===\'f\'))ACT.accept({id:o.id})');
|
||||
assert.ok(g.ev("brSold('jed','gdx')") <= g.ev("brMarket('jed','gdx')"), 'F5: no more than the route wants');
|
||||
assert.deepEqual(g.errors, []);
|
||||
});
|
||||
|
||||
test('no page errors while checking the rules', () => {
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
54
tests/gangnam.test.js
Normal file
54
tests/gangnam.test.js
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
// Gangnam Style Peering: sender pays, turned up by the scenario rule `sender` (and only there).
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const start = (ev) => ev(`beginGame('T','icn',{scn:SCN.find(x=>x.id==='gangnam')});if(UI.pendGame)ACT.pitchSkip();closeModal();S.cash=1e8`);
|
||||
const seoul = "ACT.launchBB({city:'icn'});ACT.buyTransit({city:'icn',net:'cog',tier:1});compute();for(let i=0;i<20;i++)dayTick();compute()";
|
||||
|
||||
test('sender pays: fee on Seoul transit, incumbents only over a paid PNI, cheap broadband', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
ev(seoul);
|
||||
assert.ok(ev("scnRule('sender')"));
|
||||
assert.equal(ev("R.reachable.ktt||R.reachable.skb||R.reachable.lgu"), false, 'transit does not carry the incumbents');
|
||||
assert.ok(ev('R.reach') < 0.99);
|
||||
const t = JSON.parse(ev("(()=>{const t=S.transit[0],q=R.p95[t.id];return JSON.stringify({fee:krFee(t,q),q,mo:transitMo(t,q)})})()"));
|
||||
assert.ok(t.q > 0 && t.fee === Math.round(t.q * ev('KR_FEE')), 'a sender-pays fee per Gbps of transit');
|
||||
assert.ok(ev("Math.abs(R.rev.eyeballs-R.cityEye.icn*sfOf(R,'icn')*EYE_RATE*KR_ARPU)<1"));
|
||||
ev("ACT.pni({city:'icn',net:'ktt',tier:0});closeModal();for(let i=0;i<90&&!S.pni.every(pniOn);i++)dayTick();compute()");
|
||||
assert.ok(ev('R.reachable.ktt') && ev('R.reach') >= 0.99, 'a paid PNI with Kay-Tea brings the reach');
|
||||
assert.match(ev('scnCard()'), /Seoul served well/);
|
||||
assert.match(ev('scnCard()'), /Monthly profit/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('sender pays: Korean users mind a haul to Tokyo even over peering', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
ev("ACT.launchBB({city:'icn'});UI.via=null;UI.route=null;openLinkModal('icn','tok');ACT.buildLink({tier:1});closeModal();for(const x of ixIdsIn('tok')){ACT.buyIx({city:x,tier:1,signed:true});ACT.rs({city:x});}compute()");
|
||||
assert.ok(ev('R.egT.ix') > 0 && !ev('R.egT.t'), 'only peering in Tokyo');
|
||||
assert.ok(ev('R.latF.icn') < 0.95, 'the haul costs service');
|
||||
assert.match(ev("latNote('icn')"), /Korean users notice/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('Korea outside the scenario keeps its usual prices', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("UI.startCity='icn';ACT.start({});closeModal();S.cash=1e8");
|
||||
ev(seoul);
|
||||
assert.ok(!ev("scnRule('sender')"));
|
||||
assert.ok(ev('R.reachable.ktt'), 'transit reaches the incumbents');
|
||||
assert.equal(ev("krFee(S.transit[0],100)"), 0);
|
||||
assert.ok(ev("Math.abs(R.rev.eyeballs-R.cityEye.icn*sfOf(R,'icn')*EYE_RATE)<1"));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('an older Gangnam save picks up the sender-pays rule', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
const s = ev("(()=>{const o=JSON.parse(JSON.stringify(S));o.scn.rules={};return JSON.stringify(o);})()");
|
||||
ev(`S=migrate(JSON.parse(${JSON.stringify(s)}))`);
|
||||
assert.ok(ev("S.scn.rules.sender===true"));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -100,7 +100,7 @@ test('networks in its own regions buy their transit from it, so a PNI with it re
|
|||
test('a game saved before it existed gets the courtesy route to it', () => {
|
||||
const a = load();
|
||||
a.ev("ACT.start({});S.day=40;S.seen=S.seen.filter(x=>x!=='gsl');save(true)");
|
||||
const b = load({ storage: { 'sot-save-v1': a.ev("localStorage.getItem('sot-save-v1')") } });
|
||||
const b = load({ storage: { 'sot-save-v1': a.ev("slotRaw(UI.slot)") } });
|
||||
assert.equal(b.ev("S.grace.nets.includes('gsl')"), true);
|
||||
assert.equal(b.ev("S.seen.includes('gsl')"), true);
|
||||
assert.equal(b.ev("R.reachable.gsl"), true, 'reachable through the courtesy route until you find your own way');
|
||||
|
|
|
|||
|
|
@ -27,6 +27,9 @@ function load(opts = {}) {
|
|||
window.__TUBES_TEST__ = true;
|
||||
// Seed before the game script runs, so nothing random happens at load time either.
|
||||
if (opts.seed !== false) { let r = opts.seed || 12345; window.Math.random = () => { r = (r * 16807) % 2147483647; return r / 2147483647; }; window.__reseed = (n) => { r = n; }; }
|
||||
// opts.browser (from browser()): windows of one browser share localStorage, its storage events, a broadcast
|
||||
// channel and Web Locks, like real tabs; opts.tab is one tab's sessionStorage, which survives a reload.
|
||||
if (opts.browser) opts.browser.attach(window, opts.tab || new Map(), opts);
|
||||
for (const [k, v] of Object.entries(opts.storage || {})) window.localStorage.setItem(k, v);
|
||||
if (opts.navigatorLanguage) Object.defineProperty(window.navigator, 'language', { value: opts.navigatorLanguage });
|
||||
// A non-English game: jsdom does not fetch the dictionary script, so register it up front.
|
||||
|
|
@ -62,4 +65,44 @@ function seed(ev, n) {
|
|||
ev(`if(window.__reseed)__reseed(${n});else Math.random=(()=>{let s=${n};return()=>{s=(s*16807)%2147483647;return s/2147483647;};})();`);
|
||||
}
|
||||
|
||||
module.exports = { load, seed };
|
||||
// A fake browser for several windows at once (see opts.browser). Storage events, broadcast messages and lock
|
||||
// hand-overs arrive asynchronously, as in browsers: await settle() or flush() before checking them.
|
||||
function browser({ locks = true, channel = true } = {}) {
|
||||
const ls = new Map(), wins = new Set(), held = new Map(), log = [];
|
||||
const later = (f) => setTimeout(f, 0);
|
||||
const store = (map, win, shared) => {
|
||||
const fire = (key, oldValue, newValue) => { if (shared) for (const w of wins) if (w !== win && !w.closed) later(() => { try { w.dispatchEvent(new w.StorageEvent('storage', { key, oldValue, newValue })); } catch (e) {} }); };
|
||||
return {
|
||||
getItem: (k) => { if (shared) log.push(['get', String(k)]); return map.has(String(k)) ? map.get(String(k)) : null; },
|
||||
setItem: (k, v) => { if (win.closed) return; k = String(k); v = String(v); if (shared && b.quota && k.startsWith('sot-save-v1:') && v.length > b.quota) { const e = new win.Error('full'); e.name = 'QuotaExceededError'; throw e; } const o = map.has(k) ? map.get(k) : null; map.set(k, v); if (shared) { log.push(['set', k]); fire(k, o, v); } },
|
||||
removeItem: (k) => { k = String(k); if (!map.has(k)) return; const o = map.get(k); map.delete(k); if (shared) fire(k, o, null); },
|
||||
key: (i) => [...map.keys()][i] ?? null,
|
||||
get length() { return map.size; },
|
||||
clear: () => map.clear(),
|
||||
};
|
||||
};
|
||||
const b = { ls, wins, log, quota: 0,
|
||||
attach(win, tab, opts) {
|
||||
wins.add(win);
|
||||
Object.defineProperty(win, 'localStorage', { configurable: true, get: () => store(ls, win, true) });
|
||||
Object.defineProperty(win, 'sessionStorage', { configurable: true, get: () => store(tab, win, false) });
|
||||
if (channel) win.BroadcastChannel = class { constructor(name) { this.name = name; (b.chans = b.chans || []).push({ c: this, win }); }
|
||||
postMessage(data) { const msg = JSON.parse(JSON.stringify(data)); for (const o of b.chans) if (o.c !== this && o.c.name === this.name && !o.win.closed && o.c.onmessage) later(() => o.c.onmessage({ data: msg })); }
|
||||
close() {} };
|
||||
if (locks) Object.defineProperty(win.navigator, 'locks', { configurable: true, value: {
|
||||
request(name, o, cb) {
|
||||
const cur = held.get(name);
|
||||
if (cur && !cur.win.closed && !o.steal) { if (o.ifAvailable) return win.Promise.resolve().then(() => cb(null)); return win.Promise.reject(new win.Error('busy')); }
|
||||
if (cur) { held.delete(name); cur.reject(new win.DOMException('stolen', 'AbortError')); }
|
||||
return new win.Promise((res, rej) => { const me = { win, reject: rej }; held.set(name, me);
|
||||
win.Promise.resolve().then(() => cb({ name })).then((v) => { if (held.get(name) === me) held.delete(name); res(v); }, rej); });
|
||||
} } });
|
||||
},
|
||||
// A tab closing: its locks go with it.
|
||||
close(win) { win.closed = true; for (const [k, v] of held) if (v.win === win) held.delete(k); wins.delete(win); },
|
||||
};
|
||||
return b;
|
||||
}
|
||||
const flush = (n = 3) => new Promise((r) => { const go = (i) => (i ? setTimeout(() => go(i - 1), 2) : r()); go(n); });
|
||||
|
||||
module.exports = { load, seed, browser, flush };
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
// Deliberately scan all exits for every flow, without byRank, local-city
|
||||
// shortcuts or first-group selection. Stable sorting preserves E order on ties.
|
||||
// Without Auto-TE, an exit whose shortest path from this POP is already full fits nothing, so it counts as
|
||||
// unusable, like a full exit (#210).
|
||||
module.exports = `
|
||||
for(const pass of PASSES||[null])for(const rank of RANKS){
|
||||
for(f of flows){
|
||||
|
|
@ -7,8 +9,7 @@ module.exports = `
|
|||
Dv=SDi[f.ci];Pv=SPi[f.ci];PP=walked[f.ci]||(walked[f.ci]=[]);vis++;
|
||||
// A carrier's own port (dr) is also a plain transit exit; one not set to carry only takes its own POP's traffic.
|
||||
const candidates=E.filter(e=>e.used<e.cap&&e.ok(f.n)&&
|
||||
((TR?eff(e,f.n):base(e))===rank||(dr(e,f.n)||-1)===rank)&&
|
||||
(rank!==DIRECT_RANK[1][1]&&rank!==DIRECT_RANK[2][1]||CIDX[e.city]===f.ci)&&Dv[CIDX[e.city]]<Infinity)
|
||||
(TR?eff(e,f.n):base(e,f.n))===rank&&Dv[CIDX[e.city]]<Infinity&&!gone(e))
|
||||
.sort((a,b)=>(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||Dv[CIDX[a.city]]-Dv[CIDX[b.city]]);
|
||||
for(let i=0;i<candidates.length&&f.rem>1e-6;){
|
||||
let j=i+1;while(j<candidates.length&&(candidates[j].pref==='high')===(candidates[i].pref==='high')&&
|
||||
|
|
|
|||
|
|
@ -32,12 +32,12 @@ function tour(ev) {
|
|||
for (const [label, src] of [['dash', 'ACT.dash({});ACT.dashClose()'], ['bank', 'ACT.bank();ACT.bankClose()'],
|
||||
['help', 'showHelp();closeModal()'], ['menu', 'ACT.menu();closeModal()'], ['reset', 'ACT.resetAsk();closeModal()'],
|
||||
['scenarios', 'scenarioModal();closeModal()'], ['trace', "traceModal('fra');closeModal()"],
|
||||
['route script', 'ACT.buyTE();ACT.teEdit();ACT.teExample();ACT.teCheck();closeModal()'],
|
||||
['route script', 'S.lvl=Math.max(S.lvl,3);S.cash+=1e6;ACT.coreUp();ACT.coreUp();ACT.buyTE();ACT.teEdit();ACT.teExample();ACT.teCheck();closeModal()'],
|
||||
['routers', "selectCity('fra');ACT.tab({t:'links'});ACT.models()"], ['vxc', "openVxcModal({from:'fra',to:'ams'});closeModal()"],
|
||||
['tutorial', 'S.tut=0;renderCoach();S.tut=3;renderCoach();S.tut=null;renderCoach()'], ['win', 'showWin()']]) step(label, src);
|
||||
const failSrc = ev('fireFailure.toString()');
|
||||
for (const t of ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'maxpfx', 'prepend', 'rpki', 'amp', 'roadmff', 'optic', 'ac', 'cut', 'crash', 'power', 'transit', 'ixloop', 'leak', 'ddos']) {
|
||||
const kind = ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'maxpfx', 'prepend', 'rpki', 'roadmff', 'ac'].includes(t) ? 'funny' : t;
|
||||
for (const t of ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'amp', 'roadmff', 'optic', 'ac', 'cut', 'crash', 'power', 'transit', 'ixloop', 'leak', 'ddos']) {
|
||||
const kind = ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'roadmff', 'ac'].includes(t) ? 'funny' : t;
|
||||
const patched = failSrc.replace(/^function fireFailure/, 'function')
|
||||
.replace('let tot=opts.reduce', `if(!opts.some(o=>o[0]==='${kind}'))return;opts.splice(0,opts.length,['${kind}',1]);let tot=opts.reduce`)
|
||||
.replace('type=pick(f);}', `type=f.includes('${t}')?'${t}':pick(f);}`);
|
||||
|
|
@ -82,8 +82,8 @@ test('missing translations fall back to the English, with placeholders filled',
|
|||
assert.equal(ev("tr('test.no_such_label {n}',{n:3})"), 'test.no_such_label 3', 'an unknown label comes back as it is');
|
||||
assert.equal(ev("trn('test.cats',1)"), '1 cat');
|
||||
assert.equal(ev("trn('test.cats',2)"), '2 cats');
|
||||
assert.equal(ev("trn('peering_inbox.n_day_ago',1)"), '1 giorno fa');
|
||||
assert.equal(ev("trn('peering_inbox.n_day_ago',3)"), '3 giorni fa');
|
||||
assert.equal(ev("trn('slots.n_day_ago',1)"), '1 giorno fa');
|
||||
assert.equal(ev("trn('slots.n_day_ago',3)"), '3 giorni fa');
|
||||
});
|
||||
|
||||
test('text that old saves stored in English is still translated', () => {
|
||||
|
|
@ -122,7 +122,7 @@ test('picking a language saves the choice and the game, then reloads', () => {
|
|||
ev('ACT.start({});dayTick()');
|
||||
ev("ACT.langSet({v:'it'})");
|
||||
assert.equal(ev("localStorage.getItem('sot-lang')"), 'it');
|
||||
assert.ok(ev("localStorage.getItem('sot-save-v1')"));
|
||||
assert.ok(ev("slotRaw(UI.slot)"));
|
||||
ev("ACT.langSet({v:'klingon'})");
|
||||
assert.equal(ev("localStorage.getItem('sot-lang')"), 'it');
|
||||
});
|
||||
|
|
@ -130,7 +130,7 @@ test('picking a language saves the choice and the game, then reloads', () => {
|
|||
test('a scenario started in English shows its Italian name after switching', () => {
|
||||
const en = load();
|
||||
en.ev("ACT.startScn({id:'stg'});save()");
|
||||
const { ev } = load({ lang: 'it', storage: { 'sot-save-v1': en.ev("localStorage.getItem('sot-save-v1')") } });
|
||||
const { ev } = load({ lang: 'it', storage: { 'sot-save-v1': en.ev("slotRaw(UI.slot)") } });
|
||||
const name = ev("SCN.find(x=>x.id==='stg').n");
|
||||
assert.notEqual(name, en.ev("SCN.find(x=>x.id==='stg').n"));
|
||||
assert.ok(ev("document.getElementById('hAsn').textContent").includes(name));
|
||||
|
|
@ -155,8 +155,9 @@ for (const lang of ['en', 'it', 'pt', 'fr', 'es', 'de']) {
|
|||
}
|
||||
if (lang === 'de') {
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /Spielanleitung/);
|
||||
// the link card to the real "How the Internet Works" site used to be hard-coded English
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /Wie funktioniert das Internet\?/);
|
||||
// the link card to the real "How the Internet Works" site used to be hard-coded English; it lives in How to play
|
||||
assert.match(ev("(()=>{showHelp&&showHelp();return document.getElementById('modalCard').textContent})()"), /Wie funktioniert das Internet\?/);
|
||||
ev("showTitle()");
|
||||
assert.equal(ev("document.querySelector('#hud [data-act=bank] .lbl').textContent"), 'Kasse · Bank');
|
||||
// networking jargon stays English in German (Peering, Dark Fiber); plain "fiber" is Glasfaser
|
||||
assert.equal(ev("tr('common.peering')"), 'Peering');
|
||||
|
|
|
|||
|
|
@ -1,252 +0,0 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
function setup(ev) {
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});for(const c in S.pops)S.pops[c].rgen=3;compute()");
|
||||
}
|
||||
|
||||
test('PNIs with the big networks take a month, now and then 6 to 12, and start at 100G; small ones take weeks', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:0})");
|
||||
assert.equal(ev('S.pni.length'), 0, 'no 10G PNI with NetChill');
|
||||
assert.match(ev("document.getElementById('toasts').textContent"), /does not do 10G/);
|
||||
// one order in seven gets lost in provisioning for months
|
||||
ev("Math.random=()=>0.1;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:1})");
|
||||
const p = JSON.parse(ev('JSON.stringify(S.pni[0])'));
|
||||
assert.ok(p.ready - ev('S.day') >= 180 && p.ready - ev('S.day') <= 365, `six to twelve months (${p.ready - ev('S.day')} days)`);
|
||||
ev('compute()');
|
||||
assert.equal(ev('R.usePni[S.pni[0].id]||0'), 0, 'nothing flows before delivery');
|
||||
assert.equal(ev('R.cost.pni'), 0, 'and nothing is billed');
|
||||
ev('S.nextFail=S.nextEvent=1e9;S.pni[0].ready=S.day+1;dayTick();compute()');
|
||||
assert.ok(ev('R.usePni[S.pni[0].id]') > 0, 'delivered on the day');
|
||||
// an upgrade is an augment on order: the old port keeps working meanwhile
|
||||
ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:2})");
|
||||
assert.equal(ev('S.pni[0].tier'), 1);
|
||||
assert.equal(ev('S.pni[0].up.tier'), 2);
|
||||
ev('ACT.lagP({id:S.pni[0].id,d:1})');
|
||||
assert.equal(ev('S.pni[0].up.n'), 1, 'one augment at a time');
|
||||
ev('S.day=S.pni[0].up.ready-1;dayTick()');
|
||||
assert.equal(ev('S.pni[0].tier'), 2);
|
||||
assert.equal(ev('S.pni[0].up'), undefined);
|
||||
// chasing it does nothing, mostly
|
||||
ev("Math.random=()=>0.5;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:3});const r0=S.pni[0].up.ready;ACT.pniChase({id:S.pni[0].id});window.__r=[r0,S.pni[0].up.ready]");
|
||||
const [r0, r1] = JSON.parse(ev('JSON.stringify(__r)'));
|
||||
assert.equal(r0, r1);
|
||||
// most orders arrive in about a month
|
||||
ev("Math.random=()=>0.5;S.pni=[];R.demTo.ggl=1e4;ACT.pni({city:'fra',net:'ggl',tier:1})");
|
||||
assert.equal(ev("S.pni.find(p=>p.net==='ggl').ready-S.day"), 30);
|
||||
ev("S.pni=S.pni.filter(p=>p.net!=='ggl')");
|
||||
// a beer at a conference halves the wait
|
||||
ev("Math.random=()=>0.99;S.conf={until:S.day+10,reg:'EU',name:'RIPE'}");
|
||||
assert.equal(ev("pniLead('ggl')"), 15, 'the usual month, halved');
|
||||
ev('Math.random=()=>0.1');
|
||||
assert.equal(ev("pniLead('ggl')"), Math.round((180 + Math.floor(0.1 * 186)) / 2), 'a slow one, halved');
|
||||
ev('Math.random=()=>0.99');
|
||||
ev('S.conf=null');
|
||||
// a small network: a few weeks
|
||||
const small = ev("NETS.find(n=>n.pops.includes('fra')&&!pniBig(n.id)&&n.pol==='open'&&n.type!=='cdn').id");
|
||||
ev(`Math.random=()=>0.99;ACT.pni({city:'fra',net:'${small}',tier:0})`);
|
||||
const lead = ev(`S.pni.find(p=>p.net==='${small}').ready-S.day`);
|
||||
assert.ok(lead >= 14 && lead <= 42, `weeks, not months (${lead})`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('Doitsche Telekomm sells 1G PNIs; nobody else does', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("S.lvl=10;ACT.pni({city:'fra',net:'nfx',tier:-1})");
|
||||
assert.equal(ev('S.pni.length'), 0);
|
||||
assert.equal(ev("peerOk('dtk','pni','fra').ok"), true);
|
||||
ev("ACT.pni({city:'fra',net:'dtk',tier:-1})");
|
||||
assert.equal(ev('S.pni[0].g1'), true);
|
||||
ev('S.pni[0].ready=S.day;compute()');
|
||||
assert.equal(ev('pniG(S.pni[0])'), 1);
|
||||
assert.equal(ev("liveCap(pniG(S.pni[0]),'fra','a',1)"), 1);
|
||||
assert.equal(ev('pniPN(S.pni[0])'), '1G');
|
||||
// and 1G grows into 10G
|
||||
ev("ACT.pni({city:'fra',net:'dtk',tier:0})");
|
||||
assert.equal(ev('S.pni[0].up.tier'), 0);
|
||||
ev('S.day=S.pni[0].up.ready-1;dayTick()');
|
||||
assert.equal(ev('S.pni[0].g1'), undefined);
|
||||
assert.equal(ev('pniG(S.pni[0])'), 10);
|
||||
ev("selectCity('fra');ACT.tab({t:'peer'})");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('Microsnoft has no capacity on the US east coast, at any price', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("for(const c of ['ash','nyc','hou'])ACT.buildPop({city:c});R.demTo.msf=1e5");
|
||||
for (const c of ['ash', 'nyc', 'bos', 'atn', 'mia']) {
|
||||
assert.equal(ev(`peerOk('msf','pni','${c}').ok`), false, c);
|
||||
assert.equal(ev(`peerOk('msf','ix','${c}').ok`), false, c);
|
||||
}
|
||||
assert.match(ev("peerOk('msf','pni','ash').why"), /capacity|sold out|coming online/i);
|
||||
assert.equal(ev("peerOk('msf','pni','hou').ok"), true, 'Houston is fine');
|
||||
ev("ACT.pni({city:'ash',net:'msf',tier:1})");
|
||||
assert.equal(ev("S.pni.filter(p=>p.city==='ash').length"), 0);
|
||||
assert.equal(ev("peerOk('ggl','pni','ash').ok"), ev("R.demTo.ggl>=Math.round(NET.ggl.minPni*repMul())"), 'other networks are not affected');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the peering inbox fills up, wants answers, and max-prefix alerts are growth or a leak', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});S.inbox.pol='selective';compute()");
|
||||
ev('for(let i=0;i<60;i++)dayTick()');
|
||||
assert.ok(ev('S.inbox.items.length') >= 2, 'mail arrives with an exchange port');
|
||||
assert.ok(ev('S.inbox.rep') < 0, 'and ignoring it has a price');
|
||||
// accept a real network's request: a bilateral session
|
||||
const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006&&!ixSessions('ams').has(id);})");
|
||||
assert.ok(net);
|
||||
ev(`S.inbox.items=[{id:901,k:'req',ix:'ams',net:'${net}',day:S.day,stale:false,yrs:1,say:0},{id:902,k:'req',ix:'ams',nm:'Bob’s Bits',asn:212345,day:S.day,stale:true,yrs:7,say:3}];ACT.inbox()`);
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /Bob’s Bits/);
|
||||
ev("ACT.inboxAct({id:901,a:'accept'});ACT.inboxAct({id:902,a:'accept'})");
|
||||
assert.equal(ev(`!!S.peers['${net}@ams']`), true);
|
||||
assert.equal(ev('S.inbox.tiny[212345].nm'), 'Bob’s Bits');
|
||||
ev('compute()');
|
||||
assert.equal(ev(`ixSessions('ams').has('${net}')`), true);
|
||||
// growth: raising the limit brings the session back
|
||||
ev(`S.inbox.items.push({id:903,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:180,leak:false,yrs:4});S.inbox.down['${net}@ams']=1e9`);
|
||||
assert.equal(ev(`ixSessions('ams').has('${net}')`), false, 'down on max-prefix');
|
||||
ev("ACT.inboxAct({id:903,a:'raise'})");
|
||||
assert.equal(ev(`ixSessions('ams').has('${net}')`), true);
|
||||
// a leak: raising the limit is a route leak, keeping it down is right
|
||||
ev(`S.inbox.items.push({id:904,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:987654,leak:true,yrs:4});S.inbox.down['${net}@ams']=1e9;ACT.inboxAct({id:904,a:'raise'})`);
|
||||
assert.ok(ev('S.ev.leak&&S.ev.leak.until>S.day'), 'a route leak');
|
||||
assert.ok(ev("S.inc.some(i=>i.type==='leak')"));
|
||||
ev(`S.inbox.items.push({id:905,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:987654,leak:true,yrs:4});S.inbox.down['${net}@ams']=1e9;ACT.inboxAct({id:905,a:'keep'})`);
|
||||
const back = ev(`S.inbox.down['${net}@ams']`);
|
||||
assert.ok(back > ev('S.day') && back < ev('S.day') + 12, 'back on its own in a few days');
|
||||
// unanswered requests expire, and the reputation makes selective networks pickier
|
||||
ev("S.inbox.items=[{id:906,k:'req',ix:'ams',net:'" + net + "',day:S.day-31,stale:false,yrs:1,say:0}];S.inbox.rep=0;inboxDay(S.day)");
|
||||
assert.equal(ev('S.inbox.items.some(x=>x.id===906)'), false);
|
||||
assert.ok(ev('S.inbox.rep') < 0);
|
||||
ev('S.inbox.rep=-10');
|
||||
assert.ok(ev('repMul()') > 1.05 && ev('repMul()') <= 1.1, 'pickier, but never a wall');
|
||||
// an alert nobody answers clears itself once the other side notices
|
||||
ev(`S.inbox.items=[{id:910,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:180,leak:false,yrs:4}];S.inbox.down['${net}@ams']=S.day+1;inboxDay(S.day+1)`);
|
||||
assert.equal(ev('S.inbox.items.some(x=>x.id===910)'), false);
|
||||
// bulk answers
|
||||
ev("S.inbox.items=[{id:907,k:'req',ix:'ams',nm:'A',asn:1,day:S.day,say:0,yrs:1},{id:908,k:'req',ix:'ams',nm:'B',asn:2,day:S.day,say:0,yrs:1}];ACT.inboxAll({a:'decline'})");
|
||||
assert.equal(ev('S.inbox.items.length'), 0);
|
||||
// the Networks tab says how much mail is waiting
|
||||
ev("S.inbox.items=[{id:909,k:'req',ix:'ams',nm:'C',asn:3,day:S.day,say:1,yrs:1}];closeModal();UI.left='nets';UI.leftOpen=true;renderLeft()");
|
||||
assert.match(ev("document.getElementById('left').textContent"), /Peering inbox/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the AI agent answers everything, costs $20M a year and gets it wrong a lot', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});compute()");
|
||||
const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006;})");
|
||||
const cash = ev('S.cash');
|
||||
ev("ACT.inboxBot({on:1});compute()");
|
||||
assert.equal(ev('S.inbox.bot'), true);
|
||||
assert.ok(cash - ev('S.cash') >= ev('AI_MO'));
|
||||
assert.ok(ev('R.cost.extras') >= ev('AI_MO'), 'billed every month');
|
||||
assert.ok(Math.abs(ev('AI_MO*12') - 20e6) < 12);
|
||||
// it always gets a leak wrong when the dice say so
|
||||
ev(`S.peers['${net}@ams']=true;S.inbox.items=[{id:1,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:999999,leak:true,yrs:3},{id:2,k:'req',ix:'ams',nm:'D',asn:4,day:S.day,say:0,yrs:1}];S.inbox.down['${net}@ams']=1e9`);
|
||||
ev('Math.random=()=>0.1;inboxBot()');
|
||||
assert.equal(ev('S.inbox.items.length'), 0, 'inbox zero');
|
||||
assert.ok(ev('S.ev.leak&&S.ev.leak.until>S.day'), 'and a route leak');
|
||||
assert.ok(ev("S.inbox.log.some(e=>/They seemed nice/.test(tr(e.m,e.a)))"), 'the log keeps a label, read in the language of the player');
|
||||
ev('ACT.inbox()');
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /They seemed nice/);
|
||||
// and sometimes it gets it right
|
||||
ev(`S.inbox.items=[{id:3,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:999999,leak:true,yrs:3}];S.ev.leak=null;Math.random=()=>0.9;inboxBot()`);
|
||||
assert.ok(!ev('S.ev.leak'));
|
||||
ev('ACT.inboxBot({on:0});compute()');
|
||||
assert.equal(ev('S.inbox.bot'), false);
|
||||
assert.ok(ev('R.cost.extras') < ev('AI_MO'));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('saves: the inbox and PNIs on order survive, and garbage is repaired', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("S.pni.push({id:'x',city:'fra',net:'dtk',tier:0,g1:true,ready:S.day+30,up:{tier:'9',n:99,ready:'x'}},{id:'y',city:'fra',net:'nfx',tier:1,g1:true})");
|
||||
ev("S.inbox={items:[{id:1,k:'req',ix:'ams',nm:'Ok',asn:5,day:1,say:99},{k:'evil',ix:'ams'},{id:2,k:'mp',ix:'nowhere',key:'a'},'x'],down:{'a@b':'7'},tiny:{'12':{nm:'T',ix:'ams'},'no':{ix:'ams'}},rep:99,bot:'yes',log:[{d:1,m:'hi',a:{who:{x:1}}},5],seq:'z'}");
|
||||
ev('const o=JSON.parse(JSON.stringify(S));sanitize(o);window.__o=o');
|
||||
assert.equal(ev('__o.inbox.items.length'), 1);
|
||||
assert.equal(ev('__o.inbox.items[0].say'), ev('REQ_SAY.length-1'));
|
||||
assert.equal(ev('__o.inbox.rep'), 5);
|
||||
assert.equal(ev('__o.inbox.bot'), true);
|
||||
assert.equal(ev("__o.inbox.down['a@b']"), 7);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(Object.keys(__o.inbox.tiny))')), ['12']);
|
||||
assert.equal(ev('typeof __o.inbox.log[0].a.who'), 'string');
|
||||
assert.equal(ev('__o.inbox.seq'), 1);
|
||||
assert.equal(ev("__o.pni.find(p=>p.id==='x').up.n"), ev('LAG_MAX'));
|
||||
assert.equal(ev("__o.pni.find(p=>p.id==='x').g1"), true);
|
||||
assert.equal(ev("__o.pni.find(p=>p.id==='y').g1"), undefined, 'only Doitsche Telekomm does 1G');
|
||||
// an old save without an inbox loads with an empty one
|
||||
ev('const p=JSON.parse(JSON.stringify(S));delete p.inbox;sanitize(p);window.__p=p');
|
||||
assert.equal(ev('__p.inbox.items.length'), 0);
|
||||
assert.equal(ev('__p.inbox.bot'), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('now and then a route is sold out of a wave size, for a while, and asking again does not reroll it', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3");
|
||||
assert.equal(ev("S.day=10;!!soldOut('fra','ams',3,null)||!!soldOut('fra','ams',1,null)"), false, 'never in the first 90 days');
|
||||
// find a day when 400G is sold out between Frankfurt and Amsterdam
|
||||
const day = ev("(()=>{for(let d=90;d<20000;d++){S.day=d;if(soldOut('fra','ams',2,null))return d;}return -1;})()");
|
||||
assert.ok(day > 0, 'it happens');
|
||||
ev(`S.day=${day}`);
|
||||
const so = JSON.parse(ev("JSON.stringify(soldOut('fra','ams',2,null))"));
|
||||
assert.ok(so.until > day && so.until - day <= 90);
|
||||
assert.equal(ev(`S.day=${so.until - 1};!!soldOut('fra','ams',2,null)`), true, 'the same verdict for the whole window');
|
||||
ev(`S.day=${day}`);
|
||||
const share = ev("(()=>{let n=0;for(let d=90;d<20090;d++){S.day=d;if(soldOut('ams','fra',5,null))n++;}return n/20000;})()");
|
||||
assert.ok(share > 0.02 && share < 0.2, `rare, a bit more for big waves (${share})`);
|
||||
ev(`S.day=${day};UI.via=null;openLinkModal('fra','ams')`);
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /sold out for \d+ days/);
|
||||
const n = ev('S.links.length');
|
||||
ev('ACT.buildLink({tier:2})');
|
||||
assert.equal(ev('S.links.length'), n, 'no 400G today');
|
||||
assert.match(ev("document.getElementById('toasts').textContent"), /No 400G capacity on this route/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('peering policy: open accepts everyone, selective is quieter but manual, closed scares customers; raise all limits at once', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("S.nextFail=S.nextEvent=1e9;ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});ACT.rs({city:'ams'});compute()");
|
||||
assert.equal(ev("ppol()"), 'open', 'open by default, as before');
|
||||
const rsOpen = ev("ixSessions('ams').size");
|
||||
assert.ok(rsOpen > 0, 'the route server works');
|
||||
// open: requests are accepted as they come in
|
||||
ev("Math.random=()=>0.01;inboxDay(S.day+1)");
|
||||
assert.equal(ev("S.inbox.items.filter(x=>x.k==='req').length"), 0);
|
||||
assert.ok(ev("Object.keys(S.inbox.tiny).length+Object.keys(S.peers).length") > 0, 'and they become sessions');
|
||||
// selective: the route server stops counting, you ask yourself, and requests wait for you
|
||||
ev("ACT.inboxPol({p:'selective'});compute()");
|
||||
assert.ok(ev("ixSessions('ams').size") < rsOpen, 'no route server sessions');
|
||||
ev("selectCity('ams');ACT.tab({t:'peer'})");
|
||||
assert.match(ev("document.getElementById('panelBody').textContent"), /Off while your peering policy is Selective/);
|
||||
ev("closeModal();S.inbox.items=[];inboxDay(S.day+1)");
|
||||
assert.equal(ev("S.inbox.items.filter(x=>x.k==='req').length"), 1, 'it waits for an answer');
|
||||
// closed: no requests, a sinking reputation, fewer customers calling
|
||||
ev("ACT.inboxPol({p:'closed'});S.inbox.items=[];S.inbox.rep=0;for(let i=0;i<10;i++)inboxDay(S.day+1)");
|
||||
assert.equal(ev("S.inbox.items.filter(x=>x.k==='req').length"), 0);
|
||||
assert.ok(ev('S.inbox.rep') < 0);
|
||||
// raise all: every alert at once, leaks included
|
||||
const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006;})");
|
||||
ev(`S.peers['${net}@ams']=true;S.inbox.items=[{id:71,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:80,leak:false,yrs:2},{id:72,k:'mp',key:'t9',nm:'X',asn:9,ix:'ams',day:S.day,lim:50,got:990000,leak:true,yrs:2}];S.inbox.down['${net}@ams']=1e9;ACT.inbox()`);
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /Raise all max-prefix limits/);
|
||||
ev('ACT.inboxRaiseAll()');
|
||||
assert.equal(ev("S.inbox.items.length"), 0);
|
||||
assert.equal(ev(`!!S.inbox.down['${net}@ams']`), false);
|
||||
assert.ok(ev('S.ev.leak&&S.ev.leak.until>S.day'), 'one was a leak');
|
||||
assert.match(ev("document.getElementById('toasts').textContent"), /One of them was a route leak/);
|
||||
// saves keep the policy
|
||||
ev("const o=JSON.parse(JSON.stringify(S));o.inbox.pol='weird';sanitize(o);window.__o=o");
|
||||
assert.equal(ev('__o.inbox.pol'), 'open');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -43,7 +43,7 @@ test('#5 export writes a file and import restores it, with checks', () => {
|
|||
ev(`UI.importing=parseSave(${JSON.stringify(txt)}).s;ACT.importGo()`);
|
||||
assert.equal(ev("S.name"), 'Export Me');
|
||||
assert.equal(ev("S.cash"), 1234567);
|
||||
assert.equal(ev("JSON.parse(localStorage.getItem('sot-save-v1')).name"), 'Export Me', 'saved on this device');
|
||||
assert.equal(ev("JSON.parse(slotRaw(UI.slot)).name"), 'Export Me', 'saved on this device');
|
||||
ev("showHelp()");
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /Export save.*Import a save/);
|
||||
assert.deepEqual(errors, []);
|
||||
|
|
@ -95,7 +95,7 @@ test('the network name opens a menu with save, load and start over', () => {
|
|||
ev("document.querySelector('#modalCard [data-act=resetAsk]').click()");
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /cannot be undone/);
|
||||
ev("document.querySelector('#modalCard [data-act=newgame]').click()");
|
||||
assert.equal(ev("!!localStorage.getItem('sot-save-v1')&&JSON.parse(localStorage.getItem('sot-save-v1')).day>0"), false);
|
||||
assert.equal(ev("!!slotRaw(UI.slot)&&JSON.parse(slotRaw(UI.slot)).day>0"), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
|
@ -139,7 +139,8 @@ test('Auto-TE spills overflow onto an alternate path when the shortest one is fu
|
|||
ev("for(const c of ['ams','lon','par'])ACT.buildPop({city:c});const L=(a,b,t,v)=>{UI.via=v||null;openLinkModal(a,b);ACT.buildLink({tier:t});closeModal();};L('fra','ams',0);L('ams','lon',1,'uly');L('fra','par',1);L('par','lon',1,'chn');ACT.buyTransit({city:'lon',net:'lvl',tier:1});compute()");
|
||||
const dem = ev("R.demand");
|
||||
assert.ok(ev("R.served") < dem - 1, 'without TE the 10G link caps it');
|
||||
ev("ACT.buyTE();compute()");
|
||||
// Auto-TE needs an RSVP-TE backbone, and routers that can run it: Chonk 800s.
|
||||
ev("for(const c in S.pops)S.pops[c].rgen=RG.findIndex(r=>r.n==='Chonk 800');ACT.coreUp();ACT.coreUp();ACT.buyTE();compute()");
|
||||
assert.ok(ev("R.served") > dem * 0.97, 'with TE nearly everything is served');
|
||||
assert.ok(ev("R.teMoved") > 1);
|
||||
assert.ok(ev("R.load[S.links.find(l=>l.a==='fra'&&l.b==='par').id]") > 1, 'the Paris path carries the overflow');
|
||||
|
|
@ -154,7 +155,7 @@ test('rare badges hook into incidents and deals', () => {
|
|||
const { ev, errors } = load();
|
||||
base(ev);
|
||||
ev("addInc({type:'cut',ref:'x',until:S.day+1,msg:'A crocodile took a bite. A ship dragged its anchor.'});checkGoals()");
|
||||
assert.ok(ev("S.ach.croc!==undefined&&S.ach.anchor!==undefined&&S.ach.backhoe!==undefined"));
|
||||
assert.ok(ev("S.ach.croc!==undefined&&S.ach.anchor!==undefined&&S.ach.backhoe===undefined"), "a cut alone earns no Met the Chaos Monkey");
|
||||
ev("S.stats.survived=100;checkGoals()");
|
||||
assert.ok(ev("S.ach.unbreak!==undefined"));
|
||||
assert.equal(ev("BADGES.length>=46&&new Set(BADGES.map(b=>b.id)).size===BADGES.length"), true);
|
||||
|
|
@ -356,7 +357,7 @@ test('#31 #33 #38 connections overview lists every port, filters it and jumps to
|
|||
const { ev, dom, errors } = load();
|
||||
base(ev);
|
||||
const doc = dom.window.document;
|
||||
ev("ACT.buildPop({city:'ams'});S.pops.fra.rgen=S.pops.ams.rgen=RG.length-1;S.pops.ams.bb={d:200};compute()");
|
||||
ev("ACT.buildPop({city:'ams'});S.pops.fra.rgen=S.pops.ams.rgen=RG_TOP;S.pops.ams.bb={d:200};compute()");
|
||||
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'ams',net:'lvl',tier:1});ACT.buyIx({city:'ams~3',tier:1});ACT.buyIx({city:'ams',tier:1});compute()");
|
||||
ev("S.pni.push({id:uid(),city:'fra',net:'ggl',tier:1});R.demTo.nfx=1e4;ACT.cache({city:'fra',net:'nfx'});R.demTo.nfx=1e4;ACT.cache({city:'fra',net:'nfx'});compute()");
|
||||
const all = JSON.parse(ev('JSON.stringify(conns())'));
|
||||
|
|
@ -496,7 +497,7 @@ test('#42 the share card draws links across the date line on both edges of the m
|
|||
test('#45 unplugged optics go on a spares shelf, get reused for free, or sold for 40%', () => {
|
||||
const { ev, errors } = load();
|
||||
base(ev);
|
||||
ev("S.lvl=4;ACT.buildPop({city:'ams'});S.pops.fra.rgen=S.pops.ams.rgen=RG.length-1;S.links.push({id:'df1',a:'fra',b:'ams',kind:'df',km:450,sys:'roadm',ch:[],ready:0,mo:500,day:0,cut:0});compute()");
|
||||
ev("S.lvl=4;ACT.buildPop({city:'ams'});S.pops.fra.rgen=S.pops.ams.rgen=RG_TOP;S.links.push({id:'df1',a:'fra',b:'ams',kind:'df',km:450,sys:'roadm',ch:[],ready:0,mo:500,day:0,cut:0});compute()");
|
||||
const o = ev("Object.keys(OPT).find(k=>!chWhy(S.links[0],k))");
|
||||
const c0 = ev('S.cash');
|
||||
ev(`ACT.addCh({id:'df1',o:'${o}'})`);
|
||||
|
|
@ -521,7 +522,7 @@ test('#45 unplugged optics go on a spares shelf, get reused for free, or sold fo
|
|||
test('#35 your own trench can light another fiber pair once a ROADMaster is full', () => {
|
||||
const { ev, errors } = load();
|
||||
base(ev);
|
||||
ev("S.lvl=4;ACT.buildPop({city:'ams'});S.pops.fra.rgen=S.pops.ams.rgen=RG.length-1;S.pops.fra.routers=S.pops.ams.routers=RMAX;S.links.push({id:'own1',a:'fra',b:'ams',kind:'df',own:true,km:450,sys:'roadm',ch:[],ready:0,mo:500,day:0,cut:0});compute()");
|
||||
ev("S.lvl=4;ACT.buildPop({city:'ams'});S.pops.fra.rgen=S.pops.ams.rgen=RG_TOP;S.pops.fra.routers=S.pops.ams.routers=RMAX;S.links.push({id:'own1',a:'fra',b:'ams',kind:'df',own:true,km:450,sys:'roadm',ch:[],ready:0,mo:500,day:0,cut:0});compute()");
|
||||
assert.equal(ev("chMax(S.links[0])"), 64);
|
||||
ev("ACT.addPair({id:'own1'})");
|
||||
assert.equal(ev("S.links[0].pairs||1"), 1, 'not before the first pair is full');
|
||||
|
|
@ -571,7 +572,8 @@ test('buttons behind an open modal stay quiet, and a declined PNI clears its sta
|
|||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e7;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'mrs'});ACT.buyTransit({city:'mrs',net:'cog',tier:1});compute()");
|
||||
// the PNI button was drawn while Tangerine still wanted our traffic; by the click it doesn't
|
||||
ev("R.demTo.tng=50;UI.sel={type:'city',id:'mrs'};UI.tab='peer';renderAll();R.demTo.tng=0;window.__n=0;const o=toast;toast=function(h){if(/declined/.test(h))window.__n++;return o.apply(this,arguments);}");
|
||||
// Tier 2 is folded when nothing there is worth a PNI (#175): open it, as a player would.
|
||||
ev("UI.pniOpen={t2:true};R.demTo.tng=50;UI.sel={type:'city',id:'mrs'};UI.tab='peer';renderAll();R.demTo.tng=0;window.__n=0;const o=toast;toast=function(h){if(/declined/.test(h))window.__n++;return o.apply(this,arguments);}");
|
||||
const btn = "document.querySelector('#panel [data-act=pni][data-args*=tng]')";
|
||||
assert.ok(ev(`!!${btn}`), 'a stale button to start with');
|
||||
ev(`${btn}.focus();${btn}.click()`);
|
||||
|
|
@ -1052,7 +1054,7 @@ test('#104 declining a loan offer clears the bank badge while paused', () => {
|
|||
assert.equal(ev("$('hBank').hidden"), false);
|
||||
ev("ACT.declineLoan({id:S.loanOffers[0].id})");
|
||||
assert.equal(ev("$('hBank').hidden"), true, 'badge gone without a new day');
|
||||
assert.equal(ev("JSON.parse(localStorage.getItem('sot-save-v1')).loanOffers.length"), 0, 'saved right away');
|
||||
assert.equal(ev("JSON.parse(slotRaw(UI.slot)).loanOffers.length"), 0, 'saved right away');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
|
@ -1258,23 +1260,24 @@ test('#51 a dark fiber shows what is rented out, and spare capacity can be liste
|
|||
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'ams'});S.offers=[];S.links.push({id:'df1',a:'fra',b:'ams',kind:'df',own:true,sys:'roadm',ch:['tp16','tp16'],km:450,ready:0,day:0,cut:0,mo:100,trench:'own:df1',pairs:1});after();UI.sel={type:'link',id:'df1'};renderPanel()");
|
||||
const txt = () => ev("document.getElementById('panelBody').textContent");
|
||||
assert.match(txt(), /Selling spare capacity/); assert.match(txt(), /Free channels\s*62 \/ 64/);
|
||||
// a broker finds a buyer for free channels at once, and keeps 10%
|
||||
ev("__reseed(9);ACT.advertise({id:'df1'})");
|
||||
const o = JSON.parse(ev("JSON.stringify(S.offers.find(x=>x.link==='df1'))"));
|
||||
assert.equal(o.type, 'wwave'); assert.ok(o.broker);
|
||||
assert.equal(o.rate, ev(`Math.round(waveMo(450,false,2)*0.55*${o.slots}*0.9)`), 'the usual alien-wave price minus the broker');
|
||||
assert.match(txt(), /via a capacity broker/);
|
||||
ev("ACT.advertise({id:'df1'})"); assert.equal(ev("S.offers.filter(x=>x.link==='df1').length"), 1, 'one listing at a time');
|
||||
ev(`document.querySelector('#panelBody [data-act=accept]').click()`);
|
||||
assert.ok(txt().includes(o.name), 'the customer is listed on the fiber');
|
||||
assert.match(txt(), new RegExp(`Free channels\\s*${62 - o.slots} / 64`));
|
||||
// when every channel is lit or sold, the spare pair in your own trench is offered instead; then nothing is left
|
||||
ev("const l=S.links[0];l.ch=Array(chMax(l)-soldSlots(l)).fill('tp16');after();ACT.advertise({id:'df1'})");
|
||||
assert.equal(ev("S.offers.find(x=>x.link==='df1').type"), 'dfpair');
|
||||
ev("for(const x of S.offers.filter(x=>x.link==='df1'))ACT.accept({id:x.id});S.biz.push({id:'p2',type:'dfpair',link:'df1',city:'fra',city2:'ams',name:'X',bw:1,rate:1,reqs:[]});S.offers=[];renderPanel()");
|
||||
// a broker keeps a listing and sells it as the route's market wants (#203), keeping 10%
|
||||
ev("__reseed(9);ACT.listFiber({id:'df1',w:4})");
|
||||
assert.equal(ev("S.links[0].list.w"), 4);
|
||||
assert.match(txt(), /Listed with a capacity broker/);
|
||||
ev("for(let i=0;i<120&&!S.biz.some(b=>b.link==='df1');i++)brTick();renderPanel()");
|
||||
const b = JSON.parse(ev("JSON.stringify(S.biz.find(x=>x.link==='df1'))"));
|
||||
assert.equal(b.type, 'wwave');
|
||||
assert.equal(b.rate, ev(`Math.round(waveMo(450,false,2)*0.55*${b.slots}*0.9)`), 'the usual alien-wave price minus the broker');
|
||||
assert.ok(txt().includes(b.name), 'the customer is listed on the fiber');
|
||||
assert.match(txt(), new RegExp(`Free channels\\s*${62 - b.slots} / 64`));
|
||||
assert.equal(ev("S.links[0].list?S.links[0].list.w:0"), 4 - b.slots, 'the listing shrinks by what sold');
|
||||
// when every channel is lit or sold, only the spare pair in your own trench can be listed; then nothing is left
|
||||
ev("const l=S.links[0];delete l.list;l.ch=Array(chMax(l)-soldSlots(l)).fill('tp16');after();ACT.listFiber({id:'df1',w:4,p:1})");
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links[0].list)")), { w: 0, p: 1 });
|
||||
ev("S.biz.push({id:'p1',type:'dfpair',link:'df1',city:'fra',city2:'ams',name:'X',bw:1,rate:1,reqs:[]},{id:'p2',type:'dfpair',link:'df1',city:'fra',city2:'ams',name:'Y',bw:1,rate:1,reqs:[]});delete S.links[0].list;S.offers=[];renderPanel()");
|
||||
assert.match(txt(), /Nothing spare to sell on this fiber right now/);
|
||||
ev("ACT.advertise({id:'df1'})"); assert.equal(ev("S.offers.length"), 0);
|
||||
// a broker offer survives a save, and random offers still come the same way
|
||||
ev("ACT.listFiber({id:'df1',w:1,p:1})"); assert.equal(ev("S.links[0].list===undefined"), true);
|
||||
// an old broker offer still survives a save
|
||||
ev("S.offers=[{...fiberOffer('dfpair',S.links[0],()=>'Y',0.9),broker:'yes'}];S=sanitize(S)");
|
||||
assert.equal(ev('S.offers[0].broker'), true);
|
||||
assert.deepEqual(errors, []);
|
||||
|
|
@ -1310,7 +1313,7 @@ test('#134 an exchange named after its city does not repeat the city in messages
|
|||
const labs = JSON.parse(ev("JSON.stringify(lagsN().filter(o=>o.k==='ix').map(o=>o.lab))"));
|
||||
assert.ok(labs.includes('IX.brrr Campinas LAG'), labs.join(' | '));
|
||||
assert.ok(labs.some(l => / LAG in Frankfurt$/.test(l)), labs.join(' | '));
|
||||
ev("S.inc=[];eval('('+fireFailure.toString().replace('type=pick(f);}',\"type='maxpfx';}\").replace(\"const c=pick(Object.keys(S.ixp));\",\"const c='cpq';\")+')')()");
|
||||
ev("S.inc=[];eval('('+fireFailure.toString().replace(\"if(only)type=only;\",\"type='ixloop';\").replace(\"const c=pick(Object.keys(S.ixp));\",\"const c='cpq';\")+')')()");
|
||||
const msg = ev("S.inc.map(i=>i.msg).join(' ')");
|
||||
assert.match(msg, /IX\.brrr Campinas/);
|
||||
assert.doesNotMatch(msg, /in Campinas/);
|
||||
|
|
@ -1326,3 +1329,73 @@ test('#166 every Brazilian exchange is named after its city, São Paulo included
|
|||
assert.deepEqual(odd, []);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('link redundancy trials distinguish a bridge, a full fallback and a healthy alternate path without changing the game',()=>{
|
||||
const {ev,errors}=load();
|
||||
ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'bde'});ACT.buildPop({city:'ams'});S.biz=[{id:'circuit',name:'Test Circuit',type:'l2vpn',city:'fra',city2:'bde',bw:80,rate:1,reqs:[]}];S.links=[{id:'main',a:'fra',b:'bde',kind:'wave',tier:1,km:100,mo:100,cut:0,trench:'main'}];compute();window.state=JSON.stringify(S);window.live=R;window.hot=UI.hotMap;window.cache=TE_CACHE");
|
||||
let t=JSON.parse(ev("JSON.stringify(linkTrial('main'))"));assert.equal(t.split,true);assert.equal(t.loss,80);
|
||||
assert.equal(ev('JSON.stringify(S)'),ev('state'));assert.equal(ev('R===live&&UI.hotMap===hot&&TE_CACHE===cache'),true);
|
||||
ev("S.links.push({id:'a',a:'fra',b:'ams',kind:'wave',tier:0,km:100,mo:100,cut:0},{id:'b',a:'ams',b:'bde',kind:'wave',tier:0,km:100,mo:100,cut:0});compute()");
|
||||
t=JSON.parse(ev("JSON.stringify(linkTrial('main'))"));assert.equal(t.split,false);assert.equal(t.loss,70);assert.equal(t.busy.length,2);
|
||||
ev("S.links[1].tier=1;S.links[2].tier=1;compute()");t=JSON.parse(ev("JSON.stringify(linkTrial('main'))"));assert.equal(t.split,false);assert.equal(t.loss,0);
|
||||
ev("S.links[1].cut=S.day+5;compute()");assert.equal(ev("linkTrial('main').split"),true,'existing failures are respected');assert.equal(ev("linkTrial('a')"),null,'an already failed link is not tested');
|
||||
ev("S.links=S.links.slice(0,1);S.links.push({...S.links[0],id:'parallel'});compute()");assert.equal(ev("linkTrial('main').split"),false,'only the selected link fails even when a trench is shared');assert.equal(ev("linkTrial('main').loss"),0);
|
||||
ev("S.links[0]={...S.links[0],kind:'df',sys:'roadm',ch:['tp16'],pairs:1,regen:0,ready:0,own:true};compute()");assert.equal(ev("linkTrial('main').loss"),0,'dark fiber is tested as one link');
|
||||
ev("window.innerWidth=360;ACT.linkCheck({id:'main'})");assert.match(ev("$('modalCard').textContent"),/One backhoe is not enough/);assert.equal(ev("$('modal').className"),'link-check');ev("ACT.phoneTab({t:'noc'})");assert.equal(ev("$('modal').hidden"),true);
|
||||
ev("S.links[0]={...S.links[0],kind:'vxc',vt:1,prov:FABS[0].id};compute()");assert.equal(ev("linkTrial('main').loss"),0,'virtual circuits are tested individually');
|
||||
ev("window.saveRef=S;window.liveRef=R;window.originalCompute=compute;compute=()=>{throw Error('trial failed')}");assert.throws(()=>ev("linkTrial('main')"),/trial failed/);ev('compute=originalCompute');assert.equal(ev('S===saveRef&&R===liveRef'),true,'even a failed trial restores the live state');
|
||||
assert.deepEqual(errors,[]);
|
||||
});
|
||||
|
||||
test('#219 splitting a one-member PNI across both sites splits it when the augment lands', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e8;UI.speed=0;for(const g of GOALS)S.done[g.id]=0;Object.assign(S.pops.fra,{site2:true,routers:4});S.pni.push({id:'x',net:'nfx',city:'fra',tier:1,ready:0});compute()");
|
||||
const cash = ev('S.cash');
|
||||
ev("ACT.siteSet({k:'p',id:'x',s:'ab'})");
|
||||
assert.equal(ev('S.pni[0].up.n'), 2, 'second member ordered');
|
||||
assert.equal(ev('S.pni[0].up.site'), 'ab', 'remembers the split');
|
||||
assert.ok(ev('S.cash') < cash, 'paid once');
|
||||
// clicking again while it is on order buys nothing more
|
||||
const paid = ev('S.cash');
|
||||
ev("ACT.siteSet({k:'p',id:'x',s:'ab'})");
|
||||
assert.equal(ev('S.cash'), paid);
|
||||
// the panel shows Both as chosen meanwhile
|
||||
ev("selectCity('fra');ACT.tab({t:'peer'})");
|
||||
assert.equal(ev(`[...document.querySelectorAll('[data-act=siteSet].pink')].filter(b=>JSON.parse(b.dataset.args).k==='p').map(b=>JSON.parse(b.dataset.args).s).join()`), 'ab', 'Both is shown as chosen');
|
||||
assert.equal(ev("(()=>{const m=siteCtl('p','x','fra',S.pni[0].up&&S.pni[0].up.site==='ab'?'ab':S.pni[0].site).match(/<button[^>]*class=\"[^\"]*pink[^>]*>(.*?)<\\/button>/);return m&&m[1].includes(tr('common.site'))?'':m&&m[1]})()").startsWith('Both'), true);
|
||||
// survives a save and load
|
||||
ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()');
|
||||
assert.equal(ev('S.pni[0].up.site'), 'ab');
|
||||
ev('S.day=S.pni[0].up.ready-1;dayTick()');
|
||||
assert.equal(ev('S.pni[0].n'), 2);
|
||||
assert.equal(ev('S.pni[0].site'), 'ab', 'one member in each building');
|
||||
assert.equal(ev("liveN('fra','ab',2)"), 2);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#219 choosing one site again while the augment is on order keeps the LAG in that site', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e8;UI.speed=0;for(const g of GOALS)S.done[g.id]=0;Object.assign(S.pops.fra,{site2:true,routers:4});S.pni.push({id:'x',net:'nfx',city:'fra',tier:1,ready:0});compute()");
|
||||
ev("ACT.siteSet({k:'p',id:'x',s:'ab'})");
|
||||
ev("ACT.siteSet({k:'p',id:'x',s:'b'})");
|
||||
assert.equal(ev('S.pni[0].up.site'), undefined);
|
||||
ev('S.day=S.pni[0].up.ready-1;dayTick()');
|
||||
assert.equal(ev('S.pni[0].site'), 'b');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#210 candidate exits on saturated shortest paths are skipped to avoid fallback churn', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e8;UI.speed=0;for(const g of GOALS)S.done[g.id]=0;");
|
||||
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});");
|
||||
ev("ACT.buildPop({city:'par'});ACT.launchBB({city:'par'});");
|
||||
ev("S.links.push({id:'x1',a:'fra',b:'par',kind:'wave',tier:0,km:450,mult:1,mo:1000,ready:0,cut:0});");
|
||||
ev("compute();");
|
||||
assert.ok(ev("R.load['x1'] >= 10 - 1e-6"), 'intercity wave is saturated');
|
||||
assert.ok(ev("R.load['x1'] <= 10 + 1e-6"), 'and carries no more than it can');
|
||||
// Skipping exits behind the full wave changes nothing: routing again gives the same answer.
|
||||
const first = ev('JSON.stringify([R.served,R.citySrv,R.load])');
|
||||
ev("compute();");
|
||||
assert.equal(ev('JSON.stringify([R.served,R.citySrv,R.load])'), first);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ test('changing the dropdown in Settings switches language and keeps the game', (
|
|||
const { ev, errors } = load();
|
||||
ev("ACT.start({});dayTick();ACT.settings();const s=document.getElementById('langSel');s.value='fr';s.dispatchEvent(new Event('change',{bubbles:true}))");
|
||||
assert.equal(ev("localStorage.getItem('sot-lang')"), 'fr');
|
||||
assert.ok(ev("localStorage.getItem('sot-save-v1')"), 'saved before reloading');
|
||||
assert.ok(ev("slotRaw(UI.slot)"), 'saved before reloading');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
|
|
|||
24
tests/link-trial.test.js
Normal file
24
tests/link-trial.test.js
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
// #62 on a big network: a redundancy check routes once (the failed link), and uses the live routing as "before".
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
test('#62 a redundancy check computes only the trial, and matches comparing two fresh routings', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'bde'});ACT.buildPop({city:'ams'});S.biz=[{id:'circuit',name:'Test Circuit',type:'l2vpn',city:'fra',city2:'bde',bw:80,rate:1,reqs:[]}]");
|
||||
ev("S.links=[{id:'main',a:'fra',b:'bde',kind:'wave',tier:1,km:100,mo:100,cut:0},{id:'a',a:'fra',b:'ams',kind:'wave',tier:0,km:100,mo:100,cut:0},{id:'b',a:'ams',b:'bde',kind:'wave',tier:0,km:100,mo:100,cut:0}];compute()");
|
||||
ev("window.__n=0;window.__c=compute;compute=function(){window.__n++;return window.__c.apply(this,arguments);}");
|
||||
const t = JSON.parse(ev("JSON.stringify(linkTrial('main'))"));
|
||||
assert.equal(ev('window.__n'), 1, 'one routing pass per check');
|
||||
assert.equal(t.split, false);
|
||||
assert.equal(t.loss, 70);
|
||||
assert.equal(ev("linkTrial('nope')"), null);
|
||||
assert.equal(ev('window.__n'), 1, 'an unknown link costs nothing');
|
||||
ev('compute=window.__c');
|
||||
// the old way: route the copy twice, before and after the cut
|
||||
const old = ev(`(()=>{const save=S,live=R;try{S=JSON.parse(JSON.stringify(save));compute();const b=R;S.links[0].cut=S.day+1;compute();
|
||||
const g=c=>Math.max(0,(b.citySrv[c]||0)-(R.citySrv[c]||0)),l2=Math.max(0,(b.l2.circuit||0)-(R.l2.circuit||0));
|
||||
return Object.keys(S.pops).reduce((a,c)=>a+(g(c)>.01?g(c):0),0)+(l2>.01?l2:0);}finally{S=save;R=live;}})()`);
|
||||
assert.equal(t.loss, old);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
56
tests/load-time.test.js
Normal file
56
tests/load-time.test.js
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// Work done once when a game loads (the possible-diversity map, link curves, the map's sea and hills) has shortcuts;
|
||||
// each must give exactly what the plain version gives.
|
||||
|
||||
test('diversity map: the indexed graph answers like disjointRoutes() over every possible link', (t) => {
|
||||
const { ev, dom, errors } = load(); t.after(() => dom.window.close());
|
||||
ev('ACT.start({})');
|
||||
// The plain map: one record per possible link, in the order the indexed one adds them.
|
||||
ev(`window.plainLinks=state=>{const rules=state.scn&&state.scn.rules||{},links=[],cities=CITIES.filter(c=>!(rules.banCities||[]).includes(c.id)).map(c=>c.id),add=(a,b,id)=>links.push({a,b,id});
|
||||
for(let i=0;i<cities.length;i++)for(let j=i+1;j<cities.length;j++){const a=cities[i],b=cities[j];
|
||||
if(!isSub(a,b)){add(a,b,'land:'+a+':'+b+':1');add(a,b,'land:'+a+':'+b+':2');}
|
||||
for(const c of cablesFor(a,b))if(!(rules.banPairs||[]).some(p=>p===c.cid+':'+a+'-'+b||p===c.cid+':'+b+'-'+a))add(a,b,'cab:'+c.cid);
|
||||
if(state.won&&seaCab(a,b)&&landing(a)&&landing(b)&&!cnCity(a)&&!cnCity(b))add(a,b,'own:'+a+':'+b);
|
||||
for(const f of FABS)if(f.cities.includes(a)&&f.cities.includes(b))add(a,b,'fab:'+f.id);}return links;}`);
|
||||
const cp = ev('CABLE_PAIRS[0].cid+":"+CABLE_PAIRS[0].a+"-"+CABLE_PAIRS[0].b');
|
||||
for (const st of [{ won: false }, { won: true }, { won: false, scn: { rules: { banCities: ['jam', 'lon'], banPairs: [cp] } } }]) {
|
||||
const r = JSON.parse(ev(`(()=>{const st=${JSON.stringify(st)},L=plainLinks(st);diversityMap=null;diversityPossible('fra','nyc',st);
|
||||
const ids=CITIES.map(c=>c.id),bad=[];let n=0;for(let i=0;i<ids.length;i+=3)for(let j=i+1;j<ids.length;j+=3){n++;const a=ids[i],b=ids[j];
|
||||
const want=(st.scn&&st.scn.rules.banCities.some(x=>x===a||x===b))?diversityPossible(a,b,st):disjointRoutes(a,b,L);if(diversityPossible(a,b,st)!==want)bad.push(a+'-'+b);}
|
||||
return JSON.stringify({links:L.length,mine:diversityMap.links,n,bad})})()`));
|
||||
assert.equal(r.mine, r.links, 'the same possible links');
|
||||
assert.ok(r.n > 2000);
|
||||
assert.deepEqual(r.bad, [], JSON.stringify(st));
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('link curves: skipping far-away cities gives the same bend around the ones in the way', (t) => {
|
||||
const { ev, dom, errors } = load(); t.after(() => dom.window.close());
|
||||
ev('ACT.start({})');
|
||||
// bezGeom() as it was: every other city is measured against every candidate curve.
|
||||
ev(`window.plainGeom=(l,i)=>{const A=CITY[l.a],B=CITY[l.b];const bx=A.x+wrapDx(A.x,B.x),by=B.y;const dx=bx-A.x,dy=by-A.y,len=Math.hypot(dx,dy)||1;let nx=-dy/len,ny=dx/len;if(ny>0){nx=-nx;ny=-ny;}
|
||||
const base=Math.max(4,Math.min(len*0.1,90)),step=Math.min(16,len*.06),off0=i<=0?base:(i%2?-1:1)*(base*(i%2?0.2:1)+Math.ceil(i/2)*step);const mx=(A.x+bx)/2,my=(A.y+by)/2;
|
||||
const obs=CITIES.filter(c=>c.id!==l.a&&c.id!==l.b).map(c=>[mx+wrapDx(mx,c.x),c.y]);
|
||||
const clear=(cx,cy)=>{let m=Infinity;const g={ax:A.x,ay:A.y,bx,by,cx,cy};for(let t=0.08;t<0.93;t+=0.06){const [px,py]=qpt(g,t);for(const [ox,oy] of obs){const d=Math.hypot(px-ox,py-oy);if(d<m)m=d;}}return m;};
|
||||
const sg=Math.sign(off0)||1,mag=Math.abs(off0);const need=Math.min(24,Math.max(7,len*0.2)),cap=Math.max(mag,len*0.32),lim=o=>Math.sign(o)*Math.min(Math.abs(o),cap);
|
||||
const cand=[1,1.5,2.1,2.9,3.8].map(k=>lim(sg*mag*k)).concat([1,1.5,2.1,2.9,3.8].map(k=>lim(-sg*Math.max(mag,base)*k)));let best=null,bs=-Infinity;
|
||||
for(const off of cand){const cx=mx+nx*off,cy=my+ny*off,c=clear(cx,cy);if(c>=need){best=[cx,cy];break;}const sc=Math.min(c,need)-Math.abs(off)*0.35;if(sc>bs){bs=sc;best=[cx,cy];}}
|
||||
return {ax:A.x,ay:A.y,bx,by,cx:best[0],cy:best[1],len};}`);
|
||||
const bad = JSON.parse(ev(`(()=>{const ids=CITIES.map(c=>c.id),bad=[];for(let i=0;i<ids.length;i+=6)for(let j=i+1;j<ids.length;j+=5)for(const k of [0,1,4]){
|
||||
const l={id:'x'+i+'_'+j,a:ids[i],b:ids[j]};if(JSON.stringify(bezGeom(l,k))!==JSON.stringify(plainGeom(l,k)))bad.push(l.a+'-'+l.b+'#'+k);}return JSON.stringify(bad)})()`));
|
||||
assert.deepEqual(bad, []);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('land test: the bounding box shortcut agrees with walking every coastline', (t) => {
|
||||
const { ev, dom, errors } = load(); t.after(() => dom.window.close());
|
||||
const bad = ev(`(()=>{const plain=(x,y,pts)=>{let ins=false;for(let i=0,j=pts.length-1;i<pts.length;j=i++){const [xi,yi]=pts[i],[xj,yj]=pts[j];if(((yi>y)!==(yj>y))&&(x<(xj-xi)*(y-yi)/(yj-yi)+xi))ins=!ins;}return ins;};
|
||||
let bad=0;for(let x=0;x<W;x+=7)for(let y=0;y<H;y+=7)for(const p of COAST)if(inPoly(x,y,p)!==plain(x,y,p))bad++;for(const c of CITIES)for(const p of COAST)if(inPoly(c.x,c.y,p)!==plain(c.x,c.y,p))bad++;return bad;})()`);
|
||||
assert.equal(bad, 0);
|
||||
assert.equal(ev('WAVES.length+HILLS.length'), 350);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
40
tests/metric-panel.test.js
Normal file
40
tests/metric-panel.test.js
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
// #131 on Safari: the custom metric field keeps focus through a button tap, and the panel skips re-rendering a
|
||||
// focused field, so switching between multiplier and cost (or to a preset) left the old panel on screen.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const setup = (ev) => {
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal()");
|
||||
ev("window.L=S.links[0].id;ACT.selLink({id:L});renderAll();ACT.setMetric({id:L,v:'custom'});renderAll()");
|
||||
};
|
||||
|
||||
test('#131 switching the custom metric mode re-renders even while the field has focus', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
const d = dom.window.document;
|
||||
setup(ev);
|
||||
d.getElementById('metIn').focus();
|
||||
assert.equal(d.activeElement.id, 'metIn');
|
||||
ev("ACT.metricMode({id:L,k:'w'})");
|
||||
assert.equal(d.getElementById('metIn').getAttribute('step'), '1', 'the field is now the exact cost');
|
||||
assert.equal(+d.getElementById('metIn').value, ev("S.pairMet[edgeKey(S.links[0])].v"));
|
||||
d.getElementById('metIn').focus();
|
||||
ev("ACT.metricMode({id:L,k:'f'})");
|
||||
assert.equal(d.getElementById('metIn').getAttribute('step'), '0.1', 'and back to a multiplier');
|
||||
d.getElementById('metIn').focus();
|
||||
ev("ACT.setMetric({id:L,v:'normal'})");
|
||||
assert.equal(d.getElementById('metIn'), null, 'a preset hides the field');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#131 the daily re-render still keeps a half-typed value', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
const d = dom.window.document;
|
||||
setup(ev);
|
||||
const t = d.getElementById('metIn');
|
||||
t.focus(); t.value = '3.5';
|
||||
ev("S.day++;renderPanel()");
|
||||
assert.equal(d.getElementById('metIn').value, '3.5');
|
||||
assert.equal(d.activeElement.id, 'metIn');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -149,7 +149,7 @@ test('the map draws at every zoom, with and without animations, without throwing
|
|||
test('RouteScript: parses safely, reports errors helpfully, and changes routing', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
|
||||
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'fra',net:'lvl',tier:1});ACT.buyTE();compute()");
|
||||
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'fra',net:'lvl',tier:1});ACT.coreUp();ACT.coreUp();ACT.buyTE();compute()");
|
||||
let p = JSON.parse(ev("JSON.stringify(teParse('spill at 80%\\ncap transit cogentle at 3 gbps\\nprefer ix for goggle\\nnonsense here\\navoid transit for gogle'))"));
|
||||
assert.equal(p.errors.length, 2, 'the nonsense line and the typo fail');
|
||||
assert.match(p.errors[1], /Did you mean Goggle/, 'typos get a suggestion');
|
||||
|
|
@ -176,7 +176,7 @@ test('RouteScript: parses safely, reports errors helpfully, and changes routing'
|
|||
test('RouteScript BGP: local-pref and prepending move transit, protected customers go first, the optimizer drafts a script', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
|
||||
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'fra',net:'lvl',tier:1});ACT.buyTE();for(let i=0;i<30;i++)dayTick();compute()");
|
||||
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'fra',net:'lvl',tier:1});ACT.coreUp();ACT.coreUp();ACT.buyTE();for(let i=0;i<30;i++)dayTick();compute()");
|
||||
const use = n => ev(`R.useT[S.transit.find(t=>t.net==='${n}').id]||0`);
|
||||
const p = JSON.parse(ev("JSON.stringify(teParse('prefer transit level tree\\navoid transit cogentle\\nprepend transit cogentle 2\\nprotect customers\\nprepend transit cogentle 9'))"));
|
||||
assert.equal(p.n, 4);
|
||||
|
|
@ -299,12 +299,12 @@ test('#34 scenario goal, progress and customer level are always in view', () =>
|
|||
ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderAll()");
|
||||
const left = () => dom.window.document.getElementById('leftBody').textContent;
|
||||
assert.match(left(), /Mind the Gap/);
|
||||
assert.match(left(), /POP in Bogotá/);
|
||||
assert.match(left(), /Bogotá on your network/);
|
||||
assert.match(left(), /days left/);
|
||||
assert.match(left(), /Customer level 1 of 13/);
|
||||
assert.equal(ev("$('hScn').hidden"), false, 'scenario chip in the top bar');
|
||||
const f0 = ev('scnProg().f');
|
||||
ev("S.cash=1e8;ACT.buildPop({city:'bog'});ACT.buildPop({city:'lim'});compute();renderAll()");
|
||||
ev("S.cash=1e8;UI.via='pccs';openLinkModal('pan','bog');ACT.buildLink({tier:1});closeModal();compute();renderAll()");
|
||||
assert.ok(ev('scnProg().f') > f0, 'progress moves when a goal step is reached');
|
||||
assert.match(ev("$('hScnVal').textContent"), /%/);
|
||||
assert.match(ev("$('hTier').textContent"), /Lv 1/);
|
||||
|
|
@ -358,11 +358,13 @@ test('Flood Season: attacks keep coming, grow, and only count when service held'
|
|||
assert.ok(ev('S.lvl') >= 3, 'starts with bigger gear unlocked');
|
||||
// a few weeks in: several attacks start on their own schedule
|
||||
let n = 0;
|
||||
for (let i = 0; i < 40; i++) { ev('dayTick()'); if (ev('!!(S.ev.ddos&&S.ev.ddos.start===S.day)')) n++; }
|
||||
for (let i = 0; i < 40; i++) { ev('dayTick()'); if (ev('ddosAll().some(a=>a.start===S.day)')) n++; }
|
||||
assert.ok(n >= 4, `attacks keep coming (${n} in 40 days)`);
|
||||
assert.ok(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)') >= 3, 'finished attacks are scored');
|
||||
// scoring: held only if service stayed at 97%+
|
||||
ev("S.stats.ddosOk=0;S.stats.ddosOkBig=0;S.stats.ddosLost=0;ddosDone({city:'ams',gbps:1500,worst:0.99});ddosDone({city:'ams',gbps:20,worst:0.5});ddosDone({city:'xyz',gbps:30,worst:1})");
|
||||
// scoring: held only if service stayed at 97%+, and a terabit one only with scrubbing or Flowspec
|
||||
ev("S.stats.ddosOk=0;S.stats.ddosOkBig=0;S.stats.ddosLost=0;ddosDone({city:'ams',gbps:1500,vec:'http',worst:0.99})");
|
||||
assert.equal(ev('S.stats.ddosOk+S.stats.ddosOkBig'), 1, 'held, but no terabit credit without mitigation');
|
||||
ev("S.scrubs.push({city:'ams',tier:1});S.stats.ddosOk=0;S.stats.ddosOkBig=0;S.stats.ddosLost=0;ddosDone({city:'ams',gbps:1500,worst:0.99});ddosDone({city:'ams',gbps:20,worst:0.5});ddosDone({city:'xyz',gbps:30,worst:1})");
|
||||
assert.equal(ev('S.stats.ddosOk'), 2);
|
||||
assert.equal(ev('S.stats.ddosOkBig'), 1);
|
||||
assert.equal(ev('S.stats.ddosLost'), 1);
|
||||
|
|
@ -409,8 +411,8 @@ test('#114 Only Spätzle-IX can be won by peering alone', () => {
|
|||
const { ev, errors } = load();
|
||||
ev("ACT.startScn({id:'stg',sure:1})");
|
||||
assert.equal(ev("scnRule('local')&&scnRule('noTransit')"), true);
|
||||
assert.match(ev("SCN.find(x=>x.id==='stg').goal"), /45%.*300 Gbps/);
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(scnProg().items.map(x=>x.max))")), [0.45, 300]);
|
||||
assert.match(ev("SCN.find(x=>x.id==='stg').goal"), /50%.*300 Gbps/);
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(scnProg().items.map(x=>x.max))")), [0.5, 300]);
|
||||
// a game saved before the fix picks the rule up on load
|
||||
ev("const o=JSON.parse(JSON.stringify(S));delete o.scn.rules.local;migrate(o);window.__mig=o.scn.rules.local");
|
||||
assert.equal(ev('window.__mig'), true);
|
||||
|
|
@ -433,7 +435,7 @@ test('#114 Only Spätzle-IX can be won by peering alone', () => {
|
|||
test('RouteScript: help, ready-made scripts and the AI button', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
|
||||
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'fra',net:'lvl',tier:1});ACT.buyTE();compute()");
|
||||
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'fra',net:'lvl',tier:1});ACT.coreUp();ACT.coreUp();ACT.buyTE();compute()");
|
||||
// every ready-made script parses on a real network and is listed in the help
|
||||
for (const id of JSON.parse(ev('JSON.stringify(TE_RECIPES.map(r=>r.id))')))
|
||||
assert.deepEqual(JSON.parse(ev(`JSON.stringify(teParse(TE_RECIPES.find(r=>r.id==='${id}').src().join('\\n')).errors)`)), [], id);
|
||||
|
|
@ -468,3 +470,29 @@ test('RouteScript: help, ready-made scripts and the AI button', () => {
|
|||
ev("UI.dtab='overview';renderAll()");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
||||
test('Flood Season keeps attacking and escalating after both success and timeout', () => {
|
||||
for (const outcome of ['done', 'failed']) {
|
||||
const { ev, errors, dom } = load();
|
||||
ev("ACT.startScn({id:'flood',sure:1});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9");
|
||||
if (outcome === 'done') ev('S.stats.ddosOk=20;S.stats.ddosOkBig=5;S.day=100');
|
||||
else ev('S.day=365');
|
||||
ev('scnTick(S.day)');
|
||||
assert.ok(ev(`!!S.scn.${outcome}`));
|
||||
assert.ok([...dom.window.document.querySelectorAll('#modal [data-act="closeModal"]')].some(b=>b.textContent==='Keep playing'));
|
||||
ev('ACT.closeModal();S.scn.nextDdos=S.day+1;dayTick()');
|
||||
assert.equal(ev('S.ev.ddos.start'), ev('S.day'), 'Keep playing still spawns attacks');
|
||||
const before = ev('S.day');
|
||||
ev('S.scn.nextDdos=S.day+1;S.day+=8;dayTick()');
|
||||
assert.ok(ev('ddosAll().at(-1).start') > before, 'subsequent attacks keep coming');
|
||||
// Escalating frequency belongs to spicy chaos; calmer games keep the old 3 to 7 days.
|
||||
ev("S.rules.chaos='spicy'");
|
||||
const gaps = JSON.parse(ev('const old=Math.random;Math.random=()=>0.5;S.day=0;const early=floodGap();S.day=1000;const late=floodGap();Math.random=old;JSON.stringify([early,late])'));
|
||||
assert.ok(gaps[1] < gaps[0], 'frequency keeps increasing with scenario age');
|
||||
const sizes = JSON.parse(ev('const old=Math.random;Math.random=()=>0.9;S.day=0;ddosAttack();const early=ddosAll().at(-1).gbps;S.day=1000;ddosAttack();const late=ddosAll().at(-1).gbps;Math.random=old;JSON.stringify([early,late])'));
|
||||
assert.ok(sizes[1] > sizes[0], 'intensity keeps increasing with scenario age');
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
|
|
|||
18
tests/networks-list.test.js
Normal file
18
tests/networks-list.test.js
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
test('the Networks list shows 100 networks at a time, with a button for the rest', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();UI.left='nets';UI.leftOpen=true;UI.tailOpen=false;ACT.netFilter({f:'all'})");
|
||||
const total = ev("NETS.filter(n=>!n.tail).length");
|
||||
assert.ok(total > 100, 'enough networks to page');
|
||||
const rows = () => ev("[...document.querySelectorAll('#left .row .nm .meta')].filter(e=>/^AS\\d/.test(e.textContent)).length");
|
||||
assert.equal(rows(), 100);
|
||||
assert.ok(ev("!!document.querySelector('#left [data-act=listMore]')"));
|
||||
ev("document.querySelector('#left [data-act=listMore]').click()");
|
||||
assert.equal(rows(), Math.min(total, 200));
|
||||
ev("ACT.netFilter({f:'all'})");
|
||||
assert.equal(rows(), 100, 'a new filter starts at the first page again');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -31,7 +31,7 @@ test('#186 on a phone, play after pause resumes at half speed, not the old game\
|
|||
test('#186 a saved game still continues at the speed it was saved at', () => {
|
||||
const a = load();
|
||||
a.ev("ACT.start({});ACT.speed({v:4});save(true)");
|
||||
const b = load({ storage: { 'sot-save-v1': a.ev("localStorage.getItem('sot-save-v1')") } });
|
||||
const b = load({ storage: { 'sot-save-v1': a.ev("slotRaw(UI.slot)") } });
|
||||
assert.equal(b.ev('UI.speed'), 4);
|
||||
assert.deepEqual(a.errors, []);
|
||||
assert.deepEqual(b.errors, []);
|
||||
|
|
|
|||
103
tests/optic-counts.test.js
Normal file
103
tests/optic-counts.test.js
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
const test=require('node:test');
|
||||
const assert=require('node:assert/strict');
|
||||
const {load}=require('./harness');
|
||||
function setup(ev,sub=false){ev(`ACT.start({});S.cash=1e9;S.lvl=13;S.day=100;for(const g of GOALS)S.done[g.id]=0;
|
||||
S.pops.fra.rgen=mainRG(4);S.pops.fra.routers=16;S.pops.ams={...S.pops.fra};
|
||||
S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',own:true,sub:${sub},sys:'roadm',km:400,ch:[],ready:0,day:0,cut:0,mo:1}];
|
||||
UI.sel={type:'link',id:'fiber'};renderPanel();`);}
|
||||
const count=ev=>ev('S.links[0].ch.length');
|
||||
for(const sub of [false,true])test(`typed counts buy and remove optics on ${sub?'subsea':'land'} fiber`,()=>{
|
||||
const {ev,dom,errors}=load();try{
|
||||
setup(ev,sub);const doc=dom.window.document;
|
||||
const f=doc.querySelector('form.optic-count[data-optic="zr4"]'),input=f.elements.count;
|
||||
input.focus();input.value='5';input.dispatchEvent(new dom.window.Event('input',{bubbles:true}));
|
||||
const cost=ev("5*chCost(S.links[0],'zr4')"),cash=ev('S.cash');
|
||||
assert.ok(f.querySelector('button').textContent.includes(ev(`fmt$(${cost})`)));
|
||||
ev('S.day++;renderPanel()');
|
||||
assert.equal(doc.activeElement,input,'tick preserves the focused field');assert.equal(input.value,'5');
|
||||
assert.ok(f.querySelector('button').textContent.includes(ev(`fmt$(${cost})`)));
|
||||
f.dispatchEvent(new dom.window.Event('submit',{bubbles:true,cancelable:true}));
|
||||
assert.equal(count(ev),5);assert.equal(cash-ev('S.cash'),cost);
|
||||
ev("ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),2);assert.equal(ev('S.spares.zr4'),3);
|
||||
const before=ev('S.cash');ev("ACT.setChCount({id:'fiber',o:'zr4',n:5})");assert.equal(count(ev),5);assert.equal(ev('S.cash'),before);assert.equal(ev('S.spares.zr4'),0);
|
||||
ev("ACT.setChCount({id:'fiber',o:'zr4',n:0})");assert.equal(count(ev),0);assert.equal(ev('S.spares.zr4'),5);
|
||||
assert.deepEqual(errors,[]);
|
||||
}finally{dom.window.close();}
|
||||
});
|
||||
test('batch price matches individual channel purchases with spares, regen cards and tariffs',()=>{
|
||||
const {ev,dom}=load();try{setup(ev);ev("S.links[0].regen=2;S.spares={zr4:2};S.ev.tariff=S.day+20");
|
||||
const expected=ev("2*Math.round(optCost('zr4')*REGEN_CH*2)+3*Math.round(optCost('zr4')*(1+REGEN_CH*2))");
|
||||
assert.equal(ev("opticCountCost(S.links[0],'zr4',5)"),expected);
|
||||
const cash=ev('S.cash');ev("ACT.setChCount({id:'fiber',o:'zr4',n:5})");assert.equal(cash-ev('S.cash'),expected);
|
||||
setup(ev);ev("S.links[0].regen=2;S.spares={zr4:2};S.ev.tariff=S.day+20");const cash2=ev('S.cash');
|
||||
ev("for(let i=0;i<5;i++)ACT.addCh({id:'fiber',o:'zr4'})");assert.equal(cash2-ev('S.cash'),expected);
|
||||
}finally{dom.window.close();}
|
||||
});
|
||||
test('unaffordable batches, port limits and invalid input never partially change state',()=>{
|
||||
const {ev,dom}=load();try{setup(ev);ev('S.cash=1');
|
||||
ev("ACT.setChCount({id:'fiber',o:'zr4',n:5})");assert.equal(count(ev),0);assert.equal(ev('S.cash'),1);
|
||||
ev('S.cash=1e9;S.pops.ams.routers=1');const max=ev("Math.floor(portsMax('ams')-portsUsed('ams'))");
|
||||
ev(`ACT.setChCount({id:'fiber',o:'zr4',n:${max+1}})`);assert.equal(count(ev),0);assert.equal(ev('S.cash'),1e9);
|
||||
ev('S.pops.ams.routers=16');
|
||||
for(const n of ['NaN','Infinity','-1','1.5','65',"'3'"]){ev(`ACT.setChCount({id:'fiber',o:'zr4',n:${n}})`);assert.equal(count(ev),0);}
|
||||
ev("ACT.setChCount({id:'missing',o:'zr4',n:2});ACT.setChCount({id:'fiber',o:'missing',n:2})");assert.equal(ev('S.cash'),1e9);
|
||||
}finally{dom.window.close();}
|
||||
});
|
||||
test('channel reservations and reach, line-system, level and router compatibility still apply',()=>{
|
||||
const {ev,dom}=load();try{setup(ev);
|
||||
ev("S.links[0].ch=Array(63).fill('zr8');ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),63);
|
||||
setup(ev);ev("S.biz.push({type:'wwave',link:'fiber',slots:63});ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),0);
|
||||
setup(ev);ev("S.links[0].km=20000;ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),0);
|
||||
setup(ev);ev("S.links[0].sys='lite';ACT.setChCount({id:'fiber',o:'tp16',n:2})");assert.equal(count(ev),0);
|
||||
setup(ev);ev("S.lvl=1;S.done={};ACT.setChCount({id:'fiber',o:'tp16',n:2})");assert.equal(count(ev),0);
|
||||
setup(ev);ev("S.pops.ams.rgen=0;ACT.setChCount({id:'fiber',o:'tp32',n:2})");assert.equal(count(ev),0);
|
||||
setup(ev);ev("S.links[0].ch=['zr4','zr8','zr4'];ACT.setChCount({id:'fiber',o:'zr4',n:0})");assert.equal(ev("JSON.stringify(S.links[0].ch)"),'["zr8"]');
|
||||
}finally{dom.window.close();}
|
||||
});
|
||||
test('plus and minus buttons work alongside typed counts',()=>{
|
||||
const {ev,dom,errors}=load();try{setup(ev);const doc=dom.window.document;
|
||||
const plus=()=>[...doc.querySelectorAll('[data-act="addCh"]')].find(b=>JSON.parse(b.dataset.args).o==='zr4');
|
||||
const minus=()=>[...doc.querySelectorAll('[data-act="rmCh"]')].find(b=>JSON.parse(b.dataset.args).o==='zr4');
|
||||
const input=()=>doc.querySelector('form.optic-count[data-optic="zr4"] input');
|
||||
plus().click();assert.equal(count(ev),1);assert.equal(input().value,'1');
|
||||
input().value='4';input().dispatchEvent(new dom.window.Event('input',{bubbles:true}));
|
||||
input().form.dispatchEvent(new dom.window.Event('submit',{bubbles:true,cancelable:true}));
|
||||
assert.equal(count(ev),4);minus().click();assert.equal(count(ev),3);assert.equal(input().value,'3');
|
||||
plus().click();assert.equal(count(ev),4);assert.equal(input().value,'4');assert.deepEqual(errors,[]);
|
||||
}finally{dom.window.close();}
|
||||
});
|
||||
|
||||
test('draft counts and quotes stay together when reopening a panel or using shortcuts',()=>{
|
||||
const {ev,dom}=load();try{setup(ev);const doc=dom.window.document;
|
||||
const field=()=>doc.querySelector('form.optic-count[data-optic="zr4"] input');
|
||||
field().value='5';field().dispatchEvent(new dom.window.Event('input',{bubbles:true}));
|
||||
ev("UI.sel=null;renderPanel();$('panelBody').innerHTML='';UI.sel={type:'link',id:'fiber'};renderPanel()");
|
||||
assert.equal(field().value,'5');
|
||||
ev("ACT.addCh({id:'fiber',o:'zr4'});ACT.rmCh({id:'fiber',o:'zr4'})");
|
||||
assert.equal(field().value,'0');assert.ok(field().form.querySelector('button').textContent.includes(ev('fmt$(0)')));
|
||||
field().value='';field().dispatchEvent(new dom.window.Event('input',{bubbles:true}));ev('S.day++;renderPanel()');
|
||||
assert.equal(field().value,'','empty in-progress entry survives a tick');
|
||||
}finally{dom.window.close();}
|
||||
});
|
||||
test('#229 giving up a fiber puts its optics on the spares shelf, and so does decommissioning its POP',()=>{
|
||||
const {ev,dom,errors}=load();try{
|
||||
setup(ev);
|
||||
// a leased IRU (not your own build) with mixed optics
|
||||
ev("Object.assign(S.links[0],{own:false,ch:['zr4','zr4','tp16']});S.spares={zr4:1};compute()");
|
||||
ev("ACT.rmLink({id:'fiber'})");assert.equal(ev('S.links.length'),1,'the first click only asks');
|
||||
ev("ACT.rmLink({id:'fiber'})");assert.equal(ev('S.links.length'),0,'cancelled');
|
||||
assert.equal(ev('S.spares.zr4'),3);assert.equal(ev('S.spares.tp16'),1);
|
||||
assert.match(ev("S.log.map(e=>e.t).join(' | ')"),/3 optics went back on the spares shelf/);
|
||||
// the next channel of that type uses a spare for free
|
||||
ev("S.links.push({id:'f2',a:'fra',b:'ams',kind:'df',own:true,sys:'roadm',km:400,ch:[],ready:0,day:0,cut:0,mo:1});compute()");
|
||||
const cash=ev('S.cash');ev("ACT.setChCount({id:'f2',o:'zr4',n:3})");assert.equal(ev('S.cash'),cash,'spares are used first');assert.equal(ev('S.spares.zr4'),0);
|
||||
// decommissioning a POP returns the optics of every link it takes with it
|
||||
ev("S.pops.lon={...S.pops.fra};S.links.push({id:'f3',a:'lon',b:'ams',kind:'df',own:true,sys:'roadm',km:400,ch:['tp16','tp16'],ready:0,day:0,cut:0,mo:1});compute()");
|
||||
ev("decommission(['lon'])");
|
||||
assert.equal(ev("S.links.some(l=>l.id==='f3')"),false);assert.equal(ev('S.spares.tp16'),3);
|
||||
// a link without optics says nothing about spares
|
||||
ev("S.log=[];S.links.push({id:'f4',a:'fra',b:'ams',kind:'df',own:true,sys:'roadm',km:400,ch:[],ready:0,day:0,cut:0,mo:1});compute();ACT.rmLink({id:'f4'});ACT.rmLink({id:'f4'})");
|
||||
assert.doesNotMatch(ev("S.log.map(e=>e.t).join(' | ')"),/spares shelf/);
|
||||
assert.deepEqual(errors,[]);
|
||||
}finally{dom.window.close();}
|
||||
});
|
||||
32
tests/own-asn.test.js
Normal file
32
tests/own-asn.test.js
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
test('pick your own AS number next to the name, or leave it empty for a random one (#135)', () => {
|
||||
const { ev, errors } = load();
|
||||
assert.ok(ev("!!document.querySelector('.network-name .nmwrap #nmIn')&&!!document.querySelector('.nmwrap .reroll[data-act=randomName]')"), 'round reroll button inside the name box');
|
||||
const sug = ev("+document.getElementById('asnIn').placeholder");
|
||||
assert.ok(ev(`asnOk(${sug})`), 'the suggestion is usable');
|
||||
const set = v => ev(`(()=>{const i=document.getElementById('asnIn');i.value=${JSON.stringify(v)};i.dispatchEvent(new Event('input'));return i.value})()`);
|
||||
assert.equal(set('AS 2-0-1-9-1-7'), '201917', 'only digits stay');
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()");
|
||||
assert.equal(ev('S.asn'), 201917);
|
||||
assert.match(ev("document.getElementById('hAsn').textContent"), /AS201917/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('an AS number that would not route is refused before the game starts', () => {
|
||||
const { ev, errors } = load();
|
||||
for (const bad of ['0', '23456', '64512', '4200000001', String(ev('NETS[0].asn'))]) {
|
||||
assert.equal(ev(`asnOk(${bad})`), false, bad);
|
||||
}
|
||||
ev("(()=>{const i=document.getElementById('asnIn');i.value='64512';i.dispatchEvent(new Event('input'))})()");
|
||||
assert.ok(ev("document.getElementById('asnIn').classList.contains('bad')"));
|
||||
ev('ACT.start({})');
|
||||
assert.equal(ev('S'), null, 'no game');
|
||||
assert.match(ev("document.getElementById('toasts').textContent"), /won't route/);
|
||||
ev("(()=>{const i=document.getElementById('asnIn');i.value='';i.dispatchEvent(new Event('input'))})()");
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()");
|
||||
assert.ok(ev('asnOk(S.asn)&&S.asn>=200000'), 'empty: a random one');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
117
tests/peering-desk.test.js
Normal file
117
tests/peering-desk.test.js
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
function setup(ev) {
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=6;S.nextFail=S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});compute()");
|
||||
}
|
||||
// Math.random returns these, then 0.5: [ask?, which IX, a real network?, (which one), fresh PeeringDB?]
|
||||
const seq = (ev, a) => ev(`(()=>{const q=${JSON.stringify(a)};Math.random=()=>q.length?q.shift():0.5;})()`);
|
||||
const REAL = [0.01, 0.01, 0.01, 0.01, 0.01], STALE = [0.01, 0.01, 0.9, 0.1], FRESH = [0.01, 0.01, 0.9, 0.9];
|
||||
|
||||
test('peering requests are answered by policy: Open accepts all, Selective the worthwhile ones, Closed none', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
assert.equal(ev('ppol()'), 'open', 'open by default, as before');
|
||||
const day = () => ev('peeringDeskDay(S.day)');
|
||||
const peers = () => ev("Object.keys(S.peers).filter(k=>k.endsWith('@ams')).length");
|
||||
let n = peers();
|
||||
seq(ev, REAL); day();
|
||||
assert.equal(peers(), n + 1, 'Open: a real network on the exchange gets its session at once');
|
||||
assert.ok(ev("ixSessions('ams').size") > 0);
|
||||
seq(ev, STALE); day();
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify([S.pdesk.a,S.pdesk.d])')), [2, 0], 'Open even takes the stale newcomer');
|
||||
ev("ACT.peerPol({p:'selective'})");
|
||||
assert.equal(ev('ppol()'), 'selective');
|
||||
n = peers(); seq(ev, REAL); day();
|
||||
assert.equal(peers(), n + 1, 'Selective: a real small network is worth it');
|
||||
seq(ev, STALE); day();
|
||||
seq(ev, FRESH); day();
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify([S.pdesk.a,S.pdesk.d])')), [4, 1], 'stale PeeringDB declined, up-to-date one accepted');
|
||||
ev("ACT.peerPol({p:'closed'})");
|
||||
n = peers(); seq(ev, REAL); day(); seq(ev, FRESH); day();
|
||||
assert.equal(peers(), n, 'Closed: nobody gets a session');
|
||||
assert.equal(ev('S.pdesk.d'), 3);
|
||||
ev("ACT.peerPol({p:'nope'})");
|
||||
assert.equal(ev('ppol()'), 'closed', 'junk is ignored');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('once a week the NOC log gets one folded peering desk line', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("ACT.buyIx({city:'fra',tier:1,signed:true});ACT.peerPol({p:'selective'})");
|
||||
seq(ev, [0.99]); ev('S.day=Math.ceil(S.day/7)*7+7;S.pdesk=null;peeringDeskDay(S.day)');
|
||||
const w = ev('Math.floor(S.day/7)');
|
||||
for (let i = 0; i < 6; i++) { seq(ev, i % 3 === 2 ? STALE : [0.01, i % 2 ? 0.01 : 0.99, 0.9, 0.9]); ev(`peeringDeskDay(S.day+${i})`); }
|
||||
assert.equal(ev('S.pdesk.w'), w);
|
||||
const logs = ev('S.log.length');
|
||||
seq(ev, [0.99]); ev('peeringDeskDay(S.day+7)');
|
||||
assert.equal(ev('S.log.length'), logs + 1, 'one line for the week');
|
||||
const line = ev('S.log[0].t');
|
||||
assert.match(line, /^Peering desk: 4 new sessions at .+ and .+, 2 declined \(Selective\)\.$/);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.log[0].o)')), { a: 'tab', v: 'nets' });
|
||||
assert.equal(ev('S.pdesk.w'), w + 1);
|
||||
// a quiet week says nothing
|
||||
ev('peeringDeskDay(S.day+14)');
|
||||
assert.equal(ev('S.log.length'), logs + 1);
|
||||
// the Networks tab has the policy picker, what it does, and last week's line; it fits a phone
|
||||
ev("window.innerWidth=360;UI.left='nets';UI.leftOpen=true;S.pdeskRep.w=Math.floor(S.day/7)-1;renderLeft()");
|
||||
const left = ev("document.getElementById('left').textContent");
|
||||
assert.match(left, /Peering policy: Selective/);
|
||||
assert.match(left, /newcomers with an up-to-date PeeringDB/);
|
||||
assert.match(left, /Peering desk: 4 new sessions/);
|
||||
assert.doesNotMatch(left, /inbox/i);
|
||||
ev("document.querySelector('#left [data-act=peerPol][data-args*=closed]').click()");
|
||||
assert.equal(ev('ppol()'), 'closed');
|
||||
assert.match(ev("document.getElementById('left').textContent"), /Every peering request is declined/);
|
||||
// more than four exchanges fold into "and N more"
|
||||
ev("S.pdeskRep={w:0,a:9,d:0,p:'open',ix:['ams','fra','lon','par','nyc']}");
|
||||
assert.match(ev('pdeskLine(S.pdeskRep)'), /9 new sessions at .+, .+, .+ and 2 more exchanges \(Open to all\)/);
|
||||
assert.match(ev("pdeskLine({a:0,d:1,p:'closed',ix:[]})"), /^Peering desk: 1 request declined \(Closed\)\.$/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('old saves with inbox, max-prefix and Large Peering Model state load and play', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006;})");
|
||||
ev(`S.peers['${net}@ams']=true;delete S.ppol;delete S.pdesk;delete S.pdeskRep;
|
||||
S.inbox={items:[{id:1,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:999999,leak:true,yrs:3},{id:2,k:'req',ix:'ams',nm:'D',asn:4,day:S.day,say:0,yrs:1}],
|
||||
down:{'${net}@ams':S.day+30},tiny:{'4':{nm:'D',ix:'ams'}},rep:-8,bot:true,pol:'selective',log:[{d:1,m:'peering_inbox.fire_the_ai',a:{}}],seq:2};
|
||||
S.rules={...S.rules,inbox:true};S.ev.ixdown={ams:S.day+2};
|
||||
S.inc.push({id:'m1',type:'maxpfx',ref:'ams',until:S.day+2,msg:'A member leaked the table.',cost:0,start:S.day});
|
||||
S.log.unshift({id:'l1',t:'Peering request',h:'Peering request',k:'',o:{a:'inbox'},ts:Date.now()})`);
|
||||
ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()');
|
||||
assert.equal(ev('S.inbox'), undefined, 'the inbox is gone');
|
||||
assert.equal(ev('ppol()'), 'selective', 'the policy is kept');
|
||||
assert.equal(ev("'inbox' in S.rules"), false);
|
||||
assert.equal(ev("S.inc.find(i=>i.id==='m1').type"), 'ixloop', 'a max-prefix outage in flight becomes an ordinary IX outage');
|
||||
assert.equal(ev("S.inc.some(i=>i.type==='maxpfx')"), false);
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.log.find(e=>e.id==='l1').o)")), { a: 'tab', v: 'nets' });
|
||||
assert.equal(ev(`ixSessions('ams').has('${net}')`), true, 'no session stays down on an old max-prefix limit');
|
||||
const extras = ev('R.cost.extras');
|
||||
assert.ok(extras < 20e6 / 12, 'the Large Peering Model no longer bills');
|
||||
ev("ACT.logOpen({id:'l1'})");
|
||||
assert.equal(ev('UI.left'), 'nets');
|
||||
ev('for(let i=0;i<40;i++)dayTick()');
|
||||
assert.ok(ev('S.inc.every(i=>i.type!=="maxpfx")'));
|
||||
assert.ok(ev('S.pdesk&&S.pdesk.w>=0'));
|
||||
// garbage in the new fields is repaired
|
||||
ev("const o=JSON.parse(JSON.stringify(S));o.ppol='weird';o.pdesk={w:'x',a:-5,d:1e9,ix:['ams','ams','nowhere',3]};o.pdeskRep=[1];sanitize(o);window.__o=o");
|
||||
assert.equal(ev('__o.ppol'), 'open');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(__o.pdesk)')), { w: 0, a: 0, d: 1e5, ix: ['ams'] });
|
||||
assert.equal(ev('__o.pdeskRep'), null);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('max-prefix incidents can no longer fire', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
assert.equal(ev("fireFailure.toString().includes('maxpfx')"), false);
|
||||
ev("S.day=100;const src=fireFailure.toString().replace(/^function fireFailure/,'function').replace('let tot=opts.reduce',\"opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce\");window.__ff=eval('('+src+')')");
|
||||
ev("__reseed(7);for(let i=0;i<200;i++){__ff();S.inc=S.inc.filter(x=>x.type!=='maxpfx'||(window.__mp=1,0));}");
|
||||
assert.equal(ev('!!window.__mp'), false);
|
||||
assert.equal(ev("typeof inboxDay+typeof ibx+typeof ACT.inboxRaiseAll+typeof ACT.inboxBot"), 'undefinedundefinedundefinedundefined');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -30,7 +30,7 @@ test('Rackstar requests require enough Crowdflare traffic and a free router port
|
|||
test('Rackstar serves cacheable Crowdflare traffic locally and overflow uses transit', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("S.pops.fra.rgen=RG.length-1;S.pops.fra.bb={d:200/NSH.cfl};ACT.buyTransit({city:'fra',net:'cog',tier:PORT.length-1});ACT.lagT({id:S.transit[0].id,d:1});ACT.lagT({id:S.transit[0].id,d:1});compute()");
|
||||
ev("S.pops.fra.rgen=RG_TOP;S.pops.fra.bb={d:200/NSH.cfl};ACT.buyTransit({city:'fra',net:'cog',tier:PORT.length-1});ACT.lagT({id:S.transit[0].id,d:1});ACT.lagT({id:S.transit[0].id,d:1});compute()");
|
||||
const transit = ev('R.useT[S.transit[0].id]');
|
||||
ev("ACT.cache({city:'fra',net:'cfl'})");
|
||||
assert.equal(ev('R.useCache[S.caches[0].id]'), ev('CACHE_CAP'), 'first box fills to 100G');
|
||||
|
|
@ -47,7 +47,7 @@ test('Rackstar boxes survive save migration and appear on phone peering panels i
|
|||
const { dom, ev, errors } = load(lang === 'en' ? {} : { lang });
|
||||
setup(ev);
|
||||
ev('window.matchMedia=()=>({matches:true})');
|
||||
ev("S.pops.fra.bb={d:10/NSH.cfl};compute();ACT.cache({city:'fra',net:'cfl'});save();S=migrate(JSON.parse(localStorage.getItem('sot-save-v1')));compute()");
|
||||
ev("S.pops.fra.bb={d:10/NSH.cfl};compute();ACT.cache({city:'fra',net:'cfl'});save();S=migrate(JSON.parse(slotRaw(UI.slot)));compute()");
|
||||
assert.equal(ev("S.caches.filter(x=>x.net==='cfl').length"), 1, lang);
|
||||
assert.ok(ev('R.useCache[S.caches[0].id]') > 0, lang);
|
||||
for (const [width, height] of [[360, 800], [800, 360]]) {
|
||||
|
|
@ -99,6 +99,26 @@ test('a snubbing peer tears down an existing session and the Request button expl
|
|||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('Change Freeze never refuses or tears down a session at an exchange; On-call does', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
const k = ev(`(()=>{const ok=['fra','ams','lon','par','nyc','ash','sjc','sin','tok','hkg'];
|
||||
for(let d=0;d<600;d++)for(const n of NETS)for(const c of ok){if(!ixMembers(c).includes(n.id))continue;
|
||||
S.day=d;const a=snub(n.id,c);S.day=d+1;const b=snub(n.id,c);S.day=0;if(!a&&b)return n.id+'@'+c+'@'+d;}})()`);
|
||||
assert.ok(k, 'found a snub starting at an IX');
|
||||
const [id, c, d] = k.split('@');
|
||||
ev(`S.rules=makeRules('freeze');S.day=${d}`);
|
||||
ev(`ACT.buildPop({city:'${c}'});ACT.buyIx({city:'${c}',tier:1,signed:true});S.peers['${id}@${c}']=true;compute()`);
|
||||
ev('dayTick()');
|
||||
assert.equal(ev(`!!S.peers['${id}@${c}']`), true, 'the session survives the freeze');
|
||||
assert.equal(ev(`snub('${id}','${c}')`), null, 'and nobody refuses a new one');
|
||||
assert.equal(ev(`ixSessions('${c}').has('${id}')`), true);
|
||||
assert.equal(ev('S.stats.depeered||0'), 0);
|
||||
ev(`S.rules=makeRules('oncall');S.day=${+d + 1}`);
|
||||
assert.ok(ev(`!!snub('${id}','${c}')`), 'On-call still snubs the same pair');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('remote peering is offered but costs more, gives less and gets refused more', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
|
|
@ -180,15 +200,14 @@ test('a peer at a rival exchange can de-peer you without stopping the game', ()
|
|||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('an IX meltdown at a rival exchange names the city, and a failing day tick does not stop the game', () => {
|
||||
test('an IX meltdown at a rival exchange names it, and a failing day tick does not stop the game', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'ams'});ACT.buyIx({city:'ams~2',tier:1});S.day=100");
|
||||
const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function')
|
||||
.replace('let tot=opts.reduce', "opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce")
|
||||
.replace('type=pick(f);}', "type='maxpfx';}");
|
||||
.replace('let tot=opts.reduce', "opts.splice(0,opts.length,['ixloop',1]);let tot=opts.reduce");
|
||||
ev('window.__ff=' + src);
|
||||
ev('__ff()');
|
||||
assert.match(ev("S.inc.find(i=>i.type==='maxpfx').msg"), /in Amsterdam, is down/);
|
||||
assert.ok(ev("S.inc.find(i=>i.type==='ixloop').msg.includes(ixName('ams~2'))"));
|
||||
// a tick that throws is caught, reported once, and the loop keeps going
|
||||
ev("const dt0=dayTick;window.dayTick=()=>{throw new Error('boom')};UI.speed=1;acc=DAY_MS;last=0;frame(16);window.dayTick=dt0");
|
||||
assert.equal(ev('UI.tickErr'), true);
|
||||
|
|
@ -200,7 +219,7 @@ test('Amsterdam has FRIES-IX, with free 10G and 100G ports and paid larger ports
|
|||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(ixIdsIn('ams'))")), ['ams', 'ams~2', 'ams~3']);
|
||||
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=RG.length-1;compute()");
|
||||
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=RG_TOP;compute()");
|
||||
const cash = () => ev('S.cash');
|
||||
let c0 = cash();
|
||||
assert.equal(ev("ixPortMo('ams~3',0)"), 0, '10G port is free');
|
||||
|
|
@ -221,7 +240,7 @@ test('Amsterdam has FRIES-IX, with free 10G and 100G ports and paid larger ports
|
|||
const txt = ev("document.getElementById('panelBody').textContent");
|
||||
assert.match(txt, /FRIES-IX/); assert.match(txt, /HAMS-IX/);
|
||||
assert.match(ev("ixBlock('ams~3',true)"), /LAG member <small>free/);
|
||||
ev("save();restored=migrate(JSON.parse(localStorage.getItem('sot-save-v1')));");
|
||||
ev("save();restored=migrate(JSON.parse(slotRaw(UI.slot)));");
|
||||
assert.equal(ev("restored.ixp['ams~3']"), 1, 'free port survives save migration');
|
||||
assert.equal(ev("restored.ixn['ams~3']"), 2, 'free LAG survives save migration');
|
||||
ev("S.ev.ixdown={'ams~3':S.day+2};compute()");
|
||||
|
|
@ -255,7 +274,7 @@ test('community exchanges are wired up in every city, and Barcelona has Catnip-I
|
|||
assert.equal(ev("ixName('bcn')"), 'Catnip-IX');
|
||||
for (const k of exchanges) {
|
||||
const c = k.split('~')[0];
|
||||
ev(`if(!S.pops.${c})ACT.buildPop({city:'${c}'});S.pops.${c}.rgen=RG.length-1;ACT.buyIx({city:'${k}',tier:1});ACT.rs({city:'${k}'})`);
|
||||
ev(`if(!S.pops.${c})ACT.buildPop({city:'${c}'});S.pops.${c}.rgen=RG_TOP;ACT.buyIx({city:'${k}',tier:1});ACT.rs({city:'${k}'})`);
|
||||
assert.equal(ev(`S.ixp['${k}']`), 1, `port at ${k}`);
|
||||
}
|
||||
ev('compute()');
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ const root = path.join(__dirname, '..');
|
|||
function playedGame() {
|
||||
const a = load();
|
||||
a.ev("ACT.start({});ACT.launchBB({city:'fra'});for(let i=0;i<25;i++)dayTick();UI.speed=2;save()");
|
||||
return { a, saved: a.ev("localStorage.getItem('sot-save-v1')"), day: a.ev('S.day') };
|
||||
return { a, saved: a.ev("slotRaw(UI.slot)"), day: a.ev('S.day') };
|
||||
}
|
||||
|
||||
test('a reload drops you straight back into your saved network', () => {
|
||||
|
|
@ -25,16 +25,16 @@ test('a reload drops you straight back into your saved network', () => {
|
|||
|
||||
test('leaving the page saves the game', () => {
|
||||
const a = load();
|
||||
a.ev("ACT.start({});for(let i=0;i<7;i++)dayTick();localStorage.removeItem('sot-save-v1')");
|
||||
a.ev("ACT.start({});for(let i=0;i<7;i++)dayTick();localStorage.removeItem(SLOT_K+UI.slot)");
|
||||
a.ev("dispatchEvent(new Event('pagehide'))");
|
||||
assert.equal(JSON.parse(a.ev("localStorage.getItem('sot-save-v1')")).day, a.ev('S.day'));
|
||||
assert.equal(JSON.parse(a.ev("slotRaw(UI.slot)")).day, a.ev('S.day'));
|
||||
});
|
||||
|
||||
test('a save too big for the browser is not retried every few seconds, but leaving still tries', () => {
|
||||
const a = load();
|
||||
// A storage that counts tries and refuses the game save, like a full quota.
|
||||
a.ev(`window.__tries=0;window.__full=true;const P=Object.getPrototypeOf(localStorage),set=P.setItem;
|
||||
P.setItem=function(k,v){if(k==='sot-save-v1'){__tries++;if(__full){const e=new Error('full');e.name='QuotaExceededError';throw e;}}return set.call(this,k,v);};
|
||||
P.setItem=function(k,v){if(k.startsWith('sot-save-v1')){__tries++;if(__full){const e=new Error('full');e.name='QuotaExceededError';throw e;}}return set.call(this,k,v);};
|
||||
ACT.start({});for(let i=0;i<7;i++)dayTick();__tries=0;UI.saveFail=null;save()`);
|
||||
assert.equal(a.ev('__tries'), 1);
|
||||
a.ev('save();save();after()');
|
||||
|
|
@ -44,7 +44,7 @@ test('a save too big for the browser is not retried every few seconds, but leavi
|
|||
assert.equal(a.ev('UI.saveFail.wait'), 120000, 'and each failure waits longer');
|
||||
a.ev('__full=false;UI.saveFail.at-=120001;save()');
|
||||
assert.equal(a.ev('__tries'), 3, 'tried again once the wait is over');
|
||||
assert.equal(JSON.parse(a.ev("localStorage.getItem('sot-save-v1')")).day, a.ev('S.day'));
|
||||
assert.equal(JSON.parse(a.ev("slotRaw(UI.slot)")).day, a.ev('S.day'));
|
||||
assert.equal(a.ev('UI.saveFail'), null);
|
||||
a.ev('save()');
|
||||
assert.equal(a.ev('__tries'), 4, 'a save that works keeps saving every time');
|
||||
|
|
|
|||
155
tests/pni-all.test.js
Normal file
155
tests/pni-all.test.js
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
function setup(ev, cities = []) {
|
||||
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0");
|
||||
for (const city of cities) ev(`ACT.buildPop({city:'${city}'})`);
|
||||
ev('for(const p of Object.values(S.pops))p.rgen=RG_TOP;compute()');
|
||||
}
|
||||
|
||||
test('bulk PNIs add missing shared POPs and upgrade smaller ports once, preserving existing orders and LAGs', () => {
|
||||
const { dom, ev, errors } = load();
|
||||
setup(ev, ['ams', 'lon', 'par', 'nyc', 'sjc', 'sao']);
|
||||
ev(`S.pni.push(
|
||||
{id:'small',net:'drz',city:'fra',tier:0,n:2,site:'ab',pref:'high'},
|
||||
{id:'big',net:'drz',city:'ams',tier:2},
|
||||
{id:'equal',net:'drz',city:'lon',tier:1},
|
||||
{id:'pending',net:'drz',city:'par',tier:0,ready:S.day+20},
|
||||
{id:'augment',net:'drz',city:'nyc',tier:0,up:{tier:1,n:1,ready:S.day+20}});compute()`);
|
||||
const before = ev('JSON.stringify(S)');
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify((b=>({shared:b.shared.length,orders:b.orders.length,kept:b.kept,cost:b.cost,mo:b.mo}))(pniBatch('drz',1)))")),
|
||||
{ shared: 6, orders: 2, kept: 4, cost: 6750, mo: 650 });
|
||||
assert.equal(ev('JSON.stringify(S)'), before, 'preview does not change the save');
|
||||
const cash = ev('S.cash');
|
||||
const existing = JSON.parse(ev("JSON.stringify(S.pni.filter(p=>p.id!=='small'))"));
|
||||
ev("const originalAfter=after;window.after=()=>{window.afterCount=(window.afterCount||0)+1;originalAfter()};ACT.pniAll({net:'drz',tier:1})");
|
||||
assert.equal(ev('window.afterCount'), 1, 'one recompute/render/save for the whole batch');
|
||||
assert.equal(ev('S.cash'), cash - 6750);
|
||||
assert.equal(ev('S.pni.length'), 6);
|
||||
assert.equal(ev("S.pni.filter(p=>p.city==='sao'||p.city==='tok').length"), 0, 'only shared owned POPs');
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.pni.filter(p=>['big','equal','pending','augment'].includes(p.id)))")), existing);
|
||||
assert.equal(ev("S.pni.find(p=>p.id==='small').up.n"), 2);
|
||||
assert.equal(ev("S.pni.find(p=>p.id==='small').site"), 'ab');
|
||||
assert.equal(ev("S.pni.find(p=>p.id==='small').pref"), 'high');
|
||||
assert.ok(ev("S.pni.find(p=>p.city==='sjc').ready>S.day"), 'new PNIs still take time');
|
||||
ev("ACT.pniAll({net:'drz',tier:1})");
|
||||
assert.equal(ev('S.cash'), cash - 6750, 'repeat clicks neither charge nor duplicate');
|
||||
assert.equal(ev('window.afterCount'), 1);
|
||||
ev('S=migrate(JSON.parse(JSON.stringify(packSave(S))));S.day=Math.max(...S.pni.map(p=>p.up?p.up.ready:p.ready||0));pniDay(S.day);compute()');
|
||||
assert.equal(ev("S.pni.find(p=>p.id==='small').tier"), 1, 'augment survives save migration and delivers');
|
||||
assert.equal(ev("S.pni.find(p=>p.city==='sjc').tier"), 1);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('bulk PNIs skip router speed, port capacity and policy restrictions with city-specific reasons', () => {
|
||||
const { dom, ev, errors } = load();
|
||||
setup(ev, ['ams', 'lon', 'ash']);
|
||||
ev(`S.pops.fra.rgen=0;S.pops.ams.rgen=1;
|
||||
S.caches=Array.from({length:portsMax('ams')},()=>({id:uid(),city:'ams',net:'cfl'}));
|
||||
while(['ams','lon'].some(c=>snub('msf',c)?.all))S.asn++;
|
||||
compute();R.demTo.msf=1e4;ACT.pniAllOpen({net:'msf'});ACT.pniAllSize({v:'2'})`);
|
||||
assert.equal(ev("pniBatch('msf',2).orders.length"), 1);
|
||||
assert.equal(ev("pniBatch('msf',2).blocked.length"), 3);
|
||||
const text = dom.window.document.getElementById('modalCard').textContent;
|
||||
assert.match(text, /Frankfurt.*router can't take a 400G/s);
|
||||
assert.match(text, /Amsterdam.*No free router ports/s);
|
||||
assert.match(text, /Ashburn.*capacity|Ashburn.*sold out/s);
|
||||
const cash = ev('S.cash');
|
||||
ev("ACT.pniAll({net:'msf',tier:2})");
|
||||
assert.equal(ev('S.pni.length'), 1);
|
||||
assert.equal(ev('S.pni[0].city'), 'lon');
|
||||
assert.equal(ev('S.cash'), cash - 3500);
|
||||
assert.match(ev("S.log[0].t"), /blocked: 3/);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('insufficient funds refuse the entire eligible batch and execution rechecks a stale preview', () => {
|
||||
const { dom, ev, errors } = load();
|
||||
setup(ev, ['ams']);
|
||||
ev("S.cash=pniBatch('drz',1).cost-1;ACT.pniAllOpen({net:'drz'})");
|
||||
assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true);
|
||||
const cash = ev('S.cash');
|
||||
ev("ACT.pniAll({net:'drz',tier:1})");
|
||||
assert.equal(ev('S.cash'), cash);
|
||||
assert.equal(ev('S.pni.length'), 0);
|
||||
ev("S.cash=1e8;ACT.pniAllOpen({net:'drz'});delete S.pops.ams;S.pops.fra.rgen=0;ACT.pniAll({net:'drz',tier:2})");
|
||||
assert.equal(ev('S.cash'), 1e8);
|
||||
assert.equal(ev('S.pni.length'), 0, 'deleted POPs and unsupported speeds are rechecked on click');
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('bulk PNI actions reject invalid networks, sizes, minimum ports, traffic thresholds and non-shared locations', () => {
|
||||
const { dom, ev, errors } = load();
|
||||
setup(ev);
|
||||
ev('S.pops.fra.rgen=0');
|
||||
const cash = ev('S.cash');
|
||||
for (const net of ['missing', '__proto__', 'drz', 'nfx']) {
|
||||
for (const tier of [-2, -1, 0.5, 99, NaN, Infinity]) ev(`ACT.pniAll({net:'${net}',tier:${tier}})`);
|
||||
}
|
||||
ev("ACT.pniAll({net:'nfx',tier:0});R.demTo.nfx=0;ACT.pniAll({net:'nfx',tier:1})");
|
||||
assert.equal(ev('S.pni.length'), 0);
|
||||
assert.equal(ev('S.cash'), cash);
|
||||
ev("delete S.pops.fra;ACT.pniAllOpen({net:'drz'});ACT.pniAll({net:'drz',tier:1})");
|
||||
assert.match(dom.window.document.getElementById('modalCard').textContent, /no POPs in common/);
|
||||
assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('Doitsche 1G bulk orders and 10G augments keep paid-peering fees and conference delivery rules', () => {
|
||||
const { dom, ev, errors } = load();
|
||||
setup(ev, ['ams']);
|
||||
ev("S.conf={until:S.day+10,reg:'EU'};Math.random=()=>0.5");
|
||||
const cash = ev('S.cash');
|
||||
assert.equal(ev("pniBatch('dtk',-1).cost"), 2400);
|
||||
assert.equal(ev("pniBatch('dtk',-1).mo"), ev('2*(PORT[0].pni/2+NET.dtk.paidFee)'));
|
||||
ev("ACT.pniAll({net:'dtk',tier:-1})");
|
||||
assert.equal(ev('S.cash'), cash - 2400);
|
||||
assert.equal(ev('S.stats.beerPni'), 1);
|
||||
assert.equal(ev('S.pni.every(p=>p.g1&&pniG(p)===1&&p.ready===S.day+15)'), true);
|
||||
ev('S.day+=15;pniDay(S.day);compute()');
|
||||
assert.equal(ev("pniBatch('dtk',0).mo"), 200, 'upgrades add port costs, without charging the peering fee twice');
|
||||
ev("ACT.pniAll({net:'dtk',tier:0});S.day=Math.max(...S.pni.map(p=>p.up.ready));pniDay(S.day)");
|
||||
assert.equal(ev('S.pni.every(p=>!p.g1&&pniG(p)===10)'), true);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('Traffic row buttons and size selection work by DOM events on phones in every language', () => {
|
||||
for (const lang of ['en', 'it', 'pt', 'fr', 'es']) {
|
||||
const { dom, ev, errors } = load(lang === 'en' ? {} : { lang });
|
||||
setup(ev);
|
||||
dom.window.innerWidth = 360;
|
||||
ev("ACT.launchBB({city:'fra'});ACT.dash();ACT.dashTab({k:'traffic'})");
|
||||
const doc = dom.window.document;
|
||||
const buttons = [...doc.querySelectorAll('#dashCard [data-act="pniAllOpen"]')];
|
||||
assert.ok(buttons.length > 0, lang);
|
||||
assert.equal(buttons.some(b => JSON.parse(b.dataset.args).net === '_tail'), false);
|
||||
const cash = ev('S.cash');
|
||||
buttons.find(b => JSON.parse(b.dataset.args).net === 'cfl').click();
|
||||
assert.equal(doc.getElementById('modal').hidden, false, lang);
|
||||
let select = doc.querySelector('#modalCard select');
|
||||
assert.equal(select.closest('label').textContent.includes(ev("tr('pni_all.pni_size')")), true, lang);
|
||||
select.focus();
|
||||
select.value = '0';
|
||||
select.dispatchEvent(new dom.window.Event('change', { bubbles: true }));
|
||||
select = doc.querySelector('#modalCard select');
|
||||
assert.equal(select.value, '0', lang);
|
||||
assert.equal(doc.activeElement, select, 'size changes preserve keyboard focus');
|
||||
const submit = doc.querySelector('#modalCard [data-act="pniAll"]');
|
||||
assert.equal(JSON.parse(submit.dataset.args).tier, 0, lang);
|
||||
assert.equal(submit.disabled, false, lang);
|
||||
assert.equal(ev('S.cash'), cash, 'opening or changing the preview spends nothing');
|
||||
submit.click();
|
||||
assert.equal(doc.getElementById('modal').hidden, true, lang);
|
||||
assert.equal(ev("S.pni.some(p=>p.net==='cfl'&&p.city==='fra'&&p.tier===0)"), true, lang);
|
||||
assert.equal(ev('S.cash'), cash - 1750, lang);
|
||||
assert.doesNotMatch(doc.getElementById('modalCard').textContent, /pni_all\./, lang);
|
||||
assert.deepEqual(errors, [], lang);
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
163
tests/pni-global.test.js
Normal file
163
tests/pni-global.test.js
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
function setup(ev) {
|
||||
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.pops.fra.rgen=RG_TOP;compute()");
|
||||
}
|
||||
|
||||
test('global PNIs cover every eligible network and shared POP, including the long tail, in one transaction', () => {
|
||||
const { dom, ev, errors } = load();
|
||||
setup(ev);
|
||||
ev(`ACT.buildPop({city:'ams'});S.pops.ams.rgen=RG_TOP;
|
||||
S.pni.push({id:'small',net:'cfl',city:'fra',tier:0,n:2,site:'ab',pref:'high'},
|
||||
{id:'big',net:'drz',city:'ams',tier:2},
|
||||
{id:'pending',net:'nfx',city:'fra',tier:1,ready:S.day+30});
|
||||
compute();for(const n of NETS)R.demTo[n.id]=1e4`);
|
||||
const before = ev('JSON.stringify(S)');
|
||||
const batch = JSON.parse(ev('JSON.stringify(pniBatch(null,1))'));
|
||||
assert.equal(ev('JSON.stringify(S)'), before, 'global preview changes no game state');
|
||||
assert.ok(batch.orders.some(q => q.net === 'cfl' && q.city === 'fra' && q.ex));
|
||||
assert.ok(batch.orders.some(q => q.net === 'cfl' && q.city === 'ams' && !q.ex));
|
||||
assert.ok(batch.orders.some(q => ev(`NET['${q.net}'].tail`)), 'small networks are included');
|
||||
assert.equal(batch.orders.some(q => q.net === 'drz' && q.city === 'ams'), false, 'no downgrade');
|
||||
assert.equal(batch.orders.some(q => q.net === 'nfx' && q.city === 'fra'), false, 'keep pending orders');
|
||||
const cash = ev('S.cash');
|
||||
ev("const originalAfter=after;window.after=()=>{window.afterCount=(window.afterCount||0)+1;originalAfter()};ACT.pniAll({net:null,tier:1})");
|
||||
assert.equal(ev('window.afterCount'), 1);
|
||||
assert.equal(ev('S.cash'), cash - batch.cost);
|
||||
assert.equal(ev('S.pni.length'), 3 + batch.orders.filter(q => !q.ex).length);
|
||||
assert.equal(ev('new Set(S.pni.map(p=>p.net+"@"+p.city)).size'), ev('S.pni.length'));
|
||||
assert.equal(ev("S.pni.every(p=>S.pops[p.city]&&NET[p.net].pops.includes(p.city))"), true);
|
||||
assert.equal(ev("S.pni.find(p=>p.id==='small').up.n"), 2, 'LAG members stay together');
|
||||
assert.equal(ev("S.pni.find(p=>p.id==='small').pref"), 'high');
|
||||
assert.equal(ev("S.pni.find(p=>p.id==='big').tier"), 2);
|
||||
assert.equal(ev('Object.keys(S.pops).every(c=>portsUsed(c)<=portsMax(c))'), true);
|
||||
ev('S=migrate(JSON.parse(JSON.stringify(packSave(S))));compute()');
|
||||
assert.equal(ev('S.pni.length'), 3 + batch.orders.filter(q => !q.ex).length);
|
||||
assert.equal(ev("S.pni.find(p=>p.id==='small').up.tier"), 1);
|
||||
const count = ev('S.pni.length');
|
||||
ev('ACT.pniAll({net:null,tier:1})');
|
||||
assert.equal(ev('S.cash'), cash - batch.cost, 'repeat clicks spend nothing');
|
||||
assert.equal(ev('S.pni.length'), count);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('global PNIs share the available router ports, including four 10G breakouts per slot', () => {
|
||||
for (const [tier, count] of [[1, 1], [0, 4]]) {
|
||||
const { dom, ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("S.pops.fra.rgen=0;S.caches=Array.from({length:7},()=>({id:uid(),city:'fra',net:'cfl'}));compute()");
|
||||
assert.equal(ev(`pniBatch(null,${tier}).orders.length`), count);
|
||||
assert.ok(ev(`pniBatch(null,${tier}).blocked.some(q=>/No free router ports/.test(q.why))`));
|
||||
ev(`ACT.pniAll({net:null,tier:${tier}})`);
|
||||
assert.equal(ev('S.pni.length'), count);
|
||||
assert.equal(ev("portsUsed('fra')"), 8);
|
||||
const cash = ev('S.cash');
|
||||
ev(`ACT.pniAll({net:null,tier:${tier}})`);
|
||||
assert.equal(ev('S.cash'), cash);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('global planning reserves ports for pending speed and LAG augments without mutating the save', () => {
|
||||
for (const [tier, n] of [[1, 1], [0, 4]]) {
|
||||
const { dom, ev, errors } = load();
|
||||
setup(ev);
|
||||
ev(`S.pops.fra.rgen=0;S.caches=Array.from({length:7},()=>({id:uid(),city:'fra',net:'cfl'}));
|
||||
S.pni=[{id:'pending',city:'fra',net:'cfl',tier:0,n:1,up:{tier:${tier},n:${n},ready:S.day+30}}];compute()`);
|
||||
const state = ev('JSON.stringify(S)');
|
||||
assert.equal(ev('pniBatch(null,0).orders.length'), 0);
|
||||
assert.equal(ev('pniBatch(null,1).orders.length'), 0);
|
||||
assert.equal(ev('JSON.stringify(S)'), state);
|
||||
const cash = ev('S.cash');
|
||||
ev('ACT.pniAll({net:null,tier:1})');
|
||||
assert.equal(ev('S.pni.length'), 1);
|
||||
assert.equal(ev('S.cash'), cash);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('global PNIs require the full budget and reject unsupported sizes and an empty POP list', () => {
|
||||
const { dom, ev, errors } = load();
|
||||
setup(ev);
|
||||
ev('S.cash=pniBatch(null,1).cost-1;ACT.pniAllOpen({net:null})');
|
||||
const cash = ev('S.cash');
|
||||
assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true);
|
||||
ev('ACT.pniAll({net:null,tier:1})');
|
||||
assert.equal(ev('S.cash'), cash);
|
||||
assert.equal(ev('S.pni.length'), 0, 'no partial purchase');
|
||||
for (const tier of [-2, -1, 0.5, 99, NaN, Infinity]) ev(`ACT.pniAll({net:null,tier:${tier}})`);
|
||||
ev('ACT.pniAll({tier:1});S.pops={};ACT.pniAllOpen({net:null})');
|
||||
assert.equal(ev('S.cash'), cash);
|
||||
assert.equal(ev('S.pni.length'), 0);
|
||||
assert.match(dom.window.document.getElementById('modalCard').textContent, /No shared POPs/);
|
||||
assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('the global batch, now in the Ops sheet, preserves scope, keyboard focus and translations on phones', () => {
|
||||
for (const lang of ['en', 'it', 'pt', 'fr', 'es']) {
|
||||
const { dom, ev, errors } = load(lang === 'en' ? {} : { lang });
|
||||
setup(ev);
|
||||
dom.window.innerWidth = 360;
|
||||
// The Traffic tab now points at the Ops sheet, where the one-off batches live.
|
||||
ev("ACT.dash();ACT.dashTab({k:'traffic'})");
|
||||
const doc = dom.window.document;
|
||||
doc.querySelector('#dashCard [data-act="opsOpen"]').click();
|
||||
const button = [...doc.querySelectorAll('#modalCard [data-act="pniAllOpen"]')].find(b => JSON.parse(b.dataset.args).net === null);
|
||||
assert.ok(button, lang);
|
||||
button.click();
|
||||
assert.equal(doc.querySelector('#modalCard h2').textContent, ev("tr('pni_all.peer_all_networks')"), lang);
|
||||
const cash = ev('S.cash');
|
||||
const select = doc.querySelector('#modalCard select');
|
||||
assert.equal([...select.options].some(o => o.value === '-1'), false, '1G is not available for all networks');
|
||||
select.focus();
|
||||
select.value = '0';
|
||||
select.dispatchEvent(new dom.window.Event('change', { bubbles: true }));
|
||||
assert.equal(doc.activeElement, doc.querySelector('#modalCard select'));
|
||||
const submit = doc.querySelector('#modalCard [data-act="pniAll"]');
|
||||
assert.deepEqual(JSON.parse(submit.dataset.args), { net: null, tier: 0 }, lang);
|
||||
assert.equal(submit.disabled, false, lang);
|
||||
assert.ok(doc.querySelectorAll('#modalCard details').length > 0, 'long lists are collapsed');
|
||||
assert.equal(ev('S.cash'), cash, 'preview does not buy anything');
|
||||
assert.doesNotMatch(doc.getElementById('modalCard').textContent, /pni_all\./, lang);
|
||||
const cost = ev('pniBatch(null,0).cost');
|
||||
submit.click();
|
||||
assert.equal(doc.getElementById('modal').hidden, true, lang);
|
||||
assert.equal(ev('S.cash'), cash - cost, lang);
|
||||
assert.ok(ev('new Set(S.pni.map(p=>p.net)).size') > 1, lang);
|
||||
assert.deepEqual(errors, [], lang);
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('bulk PNIs follow each network\'s own minimum port and lead time (pniMin, pniLead)', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=RG_TOP;compute();for(const n of NETS)R.demTo[n.id]=1e4");
|
||||
// Ask everyone for 10G: networks that start at 100G get 100G, the rest get 10G.
|
||||
const b = JSON.parse(ev('JSON.stringify(pniBatch(null,0))'));
|
||||
const big = b.orders.filter(q => ev(`pniMin('${q.net}')`) > 0), small = b.orders.filter(q => ev(`pniMin('${q.net}')`) === 0);
|
||||
assert.ok(big.length && small.length, 'the batch has networks of both kinds');
|
||||
assert.ok(big.every(q => q.tier === ev(`pniMin('${q.net}')`)), 'never below a network\'s minimum');
|
||||
assert.ok(small.every(q => q.tier === 0));
|
||||
assert.equal(b.raised, big.length);
|
||||
assert.equal(b.blocked.some(q => /does not do/.test(q.why)), false, 'nobody is blocked for the size alone');
|
||||
// A single network still refuses a port below its minimum.
|
||||
const t1 = ev("NETS.find(n=>pniMin(n.id)>0&&n.pops.includes('fra')).id");
|
||||
const one = JSON.parse(ev(`JSON.stringify(pniBatch('${t1}',0))`));
|
||||
assert.equal(one.orders.length, 0);
|
||||
assert.ok(one.blocked.length > 0);
|
||||
// Lead times come from pniLead per network, as for a single order: big networks about a month, others 2 to 6 weeks.
|
||||
ev("const r=Math.random;Math.random=()=>0.5;ACT.pniAll({net:null,tier:0});Math.random=r");
|
||||
const placed = JSON.parse(ev('JSON.stringify(S.pni.map(p=>({net:p.net,wait:p.ready-S.day,big:pniBig(p.net)})))'));
|
||||
assert.equal(placed.length, b.orders.length);
|
||||
assert.ok(placed.some(p => p.big) && placed.some(p => !p.big));
|
||||
for (const p of placed) if (p.big) assert.equal(p.wait, 30, p.net); else assert.equal(p.wait, 14 + Math.floor(0.5 * 29), p.net);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
135
tests/pni-list.test.js
Normal file
135
tests/pni-list.test.js
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
// The PNI list (#175, #172): how you reach each network, whether a PNI here is worth it, sorted, filtered and grouped.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// Frankfurt with 100G of Cogentle transit and 50G of eyeballs: nothing dropped, everything over transit.
|
||||
const fra = (ev, d = 50) => {
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
|
||||
ev(`S.pops.fra.bb.d=${d};S.grace=null;ACT.buyTransit({city:'fra',net:'cog',tier:1});for(const t of S.transit)t.ready=0;compute()`);
|
||||
};
|
||||
const chip = (ev, id, c = 'fra') => ev(`(()=>{const d=document.createElement('div');d.innerHTML=pniChip('${id}',${c ? `'${c}'` : 'null'});return d.textContent})()`);
|
||||
|
||||
test('one status chip per network, most direct first', () => {
|
||||
const { ev, errors } = load();
|
||||
fra(ev);
|
||||
assert.equal(chip(ev, 'ggl'), '💸 Via transit');
|
||||
// PNI here, with its size and load
|
||||
ev("S.pni.push({id:'pg',net:'ggl',city:'fra',tier:1});compute()");
|
||||
const load_ = ev("pct(R.usePni[S.pni[0].id]/100)");
|
||||
assert.equal(chip(ev, 'ggl'), `🔗 PNI here · 100G · ${load_}`);
|
||||
// On order shows as such
|
||||
ev("S.pni[0].ready=S.day+20;compute()");
|
||||
assert.equal(chip(ev, 'ggl'), '🔗 PNI here · on order');
|
||||
ev("S.pni[0].ready=0;compute()");
|
||||
// Elsewhere: the city names, and in the Networks tab (no POP) "PNI at"
|
||||
ev("for(const c of ['ams','lon','par'])S.pni.push({id:'x'+c,net:'nfx',city:c,tier:1});compute()");
|
||||
assert.equal(chip(ev, 'nfx'), '🔗 PNI elsewhere: Amsterdam, London +1');
|
||||
assert.equal(chip(ev, 'ggl', null), '🔗 PNI at Frankfurt');
|
||||
// IX session
|
||||
ev("ACT.buyIx({city:'fra',tier:1,signed:true});S.peers['akm@fra']=true;compute()");
|
||||
assert.equal(chip(ev, 'akm'), `🤝 Peers at ${ev("ixName('fra')")}`);
|
||||
// Through a peer's customer cone: named after the peer that carries it (R.cone)
|
||||
ev("S.pni.push({id:'pntt',net:'ntt',city:'fra',tier:1});compute()");
|
||||
assert.equal(ev("R.cone.voc"), 'ntt');
|
||||
assert.equal(chip(ev, 'voc'), `🧺 Via ${ev("NET.ntt.name")}'s cone`);
|
||||
// Not reached once transit goes
|
||||
ev("S.transit=[];compute()");
|
||||
assert.equal(ev("R.reachable.lvl"), false);
|
||||
assert.equal(chip(ev, 'lvl'), '🚫 Not reached');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the value line matches the transit bill by hand, and the worth-it rule', () => {
|
||||
const { ev, errors } = load();
|
||||
fra(ev);
|
||||
const v = ev("pniVal('ggl','fra')");
|
||||
const t = ev("(()=>{const t=S.transit[0];return {q:R.p95[t.id],per:transitPerG(NET[t.net],t.city,premOn(t))*S.priceMul,floor:PORT[t.tier].g*0.2}})()");
|
||||
assert.ok(v.t > 1 && v.ix === 0 && v.p === 0 && v.u < 1e-6, 'all of it over transit');
|
||||
assert.ok(t.q - v.t > t.floor, 'above the commit, so each Gbps saved is the per-Gbps price');
|
||||
assert.ok(Math.abs(v.saved - v.t * t.per) < 1e-6, 'saved = Gbps × transit price');
|
||||
assert.equal(v.cost, ev("PORT[1].pni"), 'a 100G PNI with Goggle (no fee, no per-G)');
|
||||
assert.equal(v.tier, 1, 'the smallest port Goggle accepts');
|
||||
assert.equal(v.val, v.saved - v.cost);
|
||||
assert.equal(v.worth, v.val > 0);
|
||||
// Below the commit floor nothing is saved: a tiny network has little to gain.
|
||||
const small = ev("pniVal('pst','fra')");
|
||||
assert.ok(small.g < 1 && !small.worth);
|
||||
// A full transit port drops traffic: a PNI that carries it is worth it even if it saves no transit.
|
||||
ev("S.pops.fra.bb.d=400;compute()");
|
||||
const big = ev("pniVal('nfx','fra')");
|
||||
assert.ok(big.u >= 1 && big.drop >= 1 && big.worth, 'dropped traffic makes it worth it');
|
||||
// Information only: routing is the same with or without the list reading it.
|
||||
const before = ev("JSON.stringify(R.usePni)+R.served");
|
||||
ev("renderAll();UI.sel={type:'city',id:'fra'};UI.tab='peer';renderPanel();compute()");
|
||||
assert.equal(ev("JSON.stringify(R.usePni)+R.served"), before);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the PNI list: worth it first, filters, groups by type folded when idle, phones', () => {
|
||||
const { ev, errors, dom } = load();
|
||||
dom.window.innerWidth = 360;
|
||||
fra(ev, 400);
|
||||
ev("S.pni.push({id:'pg',net:'ggl',city:'fra',tier:1});compute()");
|
||||
const panel = () => { ev("UI.sel={type:'city',id:'fra'};UI.tab='peer';UI._ph=null;renderPanel()"); return dom.window.document.getElementById('panelBody'); };
|
||||
let p = panel();
|
||||
const heads = [...p.querySelectorAll('.pgrp')].map(x => x.textContent);
|
||||
assert.ok(heads.length >= 4, 'grouped by type');
|
||||
assert.match(heads[0], /Tier 1/);
|
||||
assert.ok(heads.some(h => /Paid peering/.test(h)), 'paid networks get their own group');
|
||||
// A group with nothing worth it and no PNI stays folded; one with a worth-it network is open, best first.
|
||||
const rows = ev("(()=>{const r=NETS.filter(n=>n.pops.includes('fra')&&n.type==='cdn'&&n.pol!=='paid').map(n=>({id:n.id,v:pniVal(n.id,'fra')})).filter(x=>!S.pni.some(p=>p.net===x.id));return r})()");
|
||||
const w = rows.filter(r => r.v.worth).sort((a, b) => b.v.val - a.v.val);
|
||||
assert.ok(w.length, 'some content network is worth it at 400G of demand');
|
||||
const names = [...p.querySelectorAll('.prow .nm')].map(x => x.textContent);
|
||||
const first = ev(`NET.${w[0].id}.name`);
|
||||
assert.ok(names.some(n => n.startsWith(first) && /Worth it/.test(n)), 'best candidate is tagged');
|
||||
assert.equal(p.querySelectorAll('.prow .pchip').length, names.length, 'every row has a status chip');
|
||||
assert.ok(p.querySelector('.pval'), 'value line');
|
||||
// Filters
|
||||
ev("ACT.pniFilter({f:'pni'})");p = panel();
|
||||
assert.deepEqual([...p.querySelectorAll('.prow .nm')].map(x => x.textContent.split(' ')[0]), [ev("NET.ggl.name").split(' ')[0]]);
|
||||
ev("ACT.pniFilter({f:'worth'})");p = panel();
|
||||
assert.ok([...p.querySelectorAll('.prow .nm')].every(x => /Worth it/.test(x.textContent)));
|
||||
ev("ACT.pniFilter({f:'t'})");p = panel();
|
||||
assert.ok([...p.querySelectorAll('.pchip')].every(x => /Via transit|Not reached/.test(x.textContent)));
|
||||
// Folding and unfolding by hand, A-Z sort
|
||||
ev("ACT.pniFilter({f:'all'})");
|
||||
ev("ACT.pniGrp({g:'t1',o:0})");p = panel();
|
||||
assert.match(p.querySelector('.pgrp').textContent, /▸/);
|
||||
ev("ACT.pniGrp({g:'t1',o:1});ACT.pniSort()");p = panel();
|
||||
assert.match(p.textContent, /Sort: A–Z/);
|
||||
// Phone: chips wrap, value text stays on one line
|
||||
const css = ev("[...document.querySelectorAll('style')].map(s=>s.textContent).join('')");
|
||||
assert.match(css, /\.pchips\{display:flex;flex-wrap:wrap/);
|
||||
assert.match(css, /\.pval\{white-space:nowrap;overflow:hidden;text-overflow:ellipsis/);
|
||||
assert.equal(ev("isPhone()"), true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the same chip in the Networks tab and the bulk PNI preview', () => {
|
||||
const { ev, errors, dom } = load();
|
||||
fra(ev);
|
||||
ev("S.pni.push({id:'pg',net:'ggl',city:'fra',tier:1});compute()");
|
||||
ev("UI.sel=null;UI.left='nets';UI.leftOpen=true;UI._lh=null;renderLeft()");
|
||||
const left = dom.window.document.getElementById('leftBody');
|
||||
assert.ok(left.querySelectorAll('.pchip').length >= 10);
|
||||
assert.ok(/PNI at Frankfurt/.test(left.textContent), 'Goggle shows its PNI');
|
||||
ev("ACT.pniAllOpen({net:null})");
|
||||
const m = dom.window.document.getElementById('modal');
|
||||
assert.ok(m.querySelectorAll('.pchip').length > 0);
|
||||
assert.ok(/Via transit/.test(m.textContent), 'bulk preview chips');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('every language renders the PNI list without raw labels', () => {
|
||||
for (const lang of ['de', 'es', 'fr', 'it', 'pt']) {
|
||||
const { ev, errors, dom } = load({ lang });
|
||||
fra(ev, 400);
|
||||
ev("UI.sel={type:'city',id:'fra'};UI.tab='peer';renderPanel();UI.left='nets';UI.leftOpen=true;renderLeft()");
|
||||
const txt = dom.window.document.getElementById('panelBody').textContent + dom.window.document.getElementById('leftBody').textContent;
|
||||
assert.doesNotMatch(txt, /pni_list\./, lang);
|
||||
assert.ok(dom.window.document.querySelector('#panelBody .pchip'), lang);
|
||||
assert.deepEqual(errors, [], lang);
|
||||
}
|
||||
});
|
||||
146
tests/pnis-and-sold-out.test.js
Normal file
146
tests/pnis-and-sold-out.test.js
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
function setup(ev) {
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});for(const c in S.pops)S.pops[c].rgen=3;compute()");
|
||||
}
|
||||
|
||||
test('PNIs with the big networks take a month, now and then 6 to 12, and start at 100G; small ones take weeks', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:0})");
|
||||
assert.equal(ev('S.pni.length'), 0, 'no 10G PNI with NetChill');
|
||||
assert.match(ev("document.getElementById('toasts').textContent"), /does not do 10G/);
|
||||
// one order in seven gets lost in provisioning for months
|
||||
ev("Math.random=()=>0.1;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:1})");
|
||||
const p = JSON.parse(ev('JSON.stringify(S.pni[0])'));
|
||||
assert.ok(p.ready - ev('S.day') >= 180 && p.ready - ev('S.day') <= 365, `six to twelve months (${p.ready - ev('S.day')} days)`);
|
||||
ev('compute()');
|
||||
assert.equal(ev('R.usePni[S.pni[0].id]||0'), 0, 'nothing flows before delivery');
|
||||
assert.equal(ev('R.cost.pni'), 0, 'and nothing is billed');
|
||||
ev('S.nextFail=S.nextEvent=1e9;S.pni[0].ready=S.day+1;dayTick();compute()');
|
||||
assert.ok(ev('R.usePni[S.pni[0].id]') > 0, 'delivered on the day');
|
||||
// an upgrade is an augment on order: the old port keeps working meanwhile
|
||||
ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:2})");
|
||||
assert.equal(ev('S.pni[0].tier'), 1);
|
||||
assert.equal(ev('S.pni[0].up.tier'), 2);
|
||||
ev('ACT.lagP({id:S.pni[0].id,d:1})');
|
||||
assert.equal(ev('S.pni[0].up.n'), 1, 'one augment at a time');
|
||||
ev('S.day=S.pni[0].up.ready-1;dayTick()');
|
||||
assert.equal(ev('S.pni[0].tier'), 2);
|
||||
assert.equal(ev('S.pni[0].up'), undefined);
|
||||
// chasing it does nothing, mostly
|
||||
ev("Math.random=()=>0.5;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:3});const r0=S.pni[0].up.ready;ACT.pniChase({id:S.pni[0].id});window.__r=[r0,S.pni[0].up.ready]");
|
||||
const [r0, r1] = JSON.parse(ev('JSON.stringify(__r)'));
|
||||
assert.equal(r0, r1);
|
||||
// most orders arrive in about a month
|
||||
ev("Math.random=()=>0.5;S.pni=[];R.demTo.ggl=1e4;ACT.pni({city:'fra',net:'ggl',tier:1})");
|
||||
assert.equal(ev("S.pni.find(p=>p.net==='ggl').ready-S.day"), 30);
|
||||
ev("S.pni=S.pni.filter(p=>p.net!=='ggl')");
|
||||
// a beer at a conference halves the wait
|
||||
ev("Math.random=()=>0.99;S.conf={until:S.day+10,reg:'EU',name:'RIPE'}");
|
||||
assert.equal(ev("pniLead('ggl')"), 15, 'the usual month, halved');
|
||||
ev('Math.random=()=>0.1');
|
||||
assert.equal(ev("pniLead('ggl')"), Math.round((180 + Math.floor(0.1 * 186)) / 2), 'a slow one, halved');
|
||||
ev('Math.random=()=>0.99');
|
||||
ev('S.conf=null');
|
||||
// a small network: a few weeks
|
||||
const small = ev("NETS.find(n=>n.pops.includes('fra')&&!pniBig(n.id)&&n.pol==='open'&&n.type!=='cdn').id");
|
||||
ev(`Math.random=()=>0.99;ACT.pni({city:'fra',net:'${small}',tier:0})`);
|
||||
const lead = ev(`S.pni.find(p=>p.net==='${small}').ready-S.day`);
|
||||
assert.ok(lead >= 14 && lead <= 42, `weeks, not months (${lead})`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('Doitsche Telekomm sells 1G PNIs; nobody else does', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("S.lvl=10;ACT.pni({city:'fra',net:'nfx',tier:-1})");
|
||||
assert.equal(ev('S.pni.length'), 0);
|
||||
assert.equal(ev("peerOk('dtk','pni','fra').ok"), true);
|
||||
ev("ACT.pni({city:'fra',net:'dtk',tier:-1})");
|
||||
assert.equal(ev('S.pni[0].g1'), true);
|
||||
ev('S.pni[0].ready=S.day;compute()');
|
||||
assert.equal(ev('pniG(S.pni[0])'), 1);
|
||||
assert.equal(ev("liveCap(pniG(S.pni[0]),'fra','a',1)"), 1);
|
||||
assert.equal(ev('pniPN(S.pni[0])'), '1G');
|
||||
// and 1G grows into 10G
|
||||
ev("ACT.pni({city:'fra',net:'dtk',tier:0})");
|
||||
assert.equal(ev('S.pni[0].up.tier'), 0);
|
||||
ev('S.day=S.pni[0].up.ready-1;dayTick()');
|
||||
assert.equal(ev('S.pni[0].g1'), undefined);
|
||||
assert.equal(ev('pniG(S.pni[0])'), 10);
|
||||
ev("selectCity('fra');ACT.tab({t:'peer'})");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('Microsnoft has no capacity on the US east coast, at any price', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("for(const c of ['ash','nyc','hou'])ACT.buildPop({city:c});R.demTo.msf=1e5");
|
||||
for (const c of ['ash', 'nyc', 'bos', 'atn', 'mia']) {
|
||||
assert.equal(ev(`peerOk('msf','pni','${c}').ok`), false, c);
|
||||
assert.equal(ev(`peerOk('msf','ix','${c}').ok`), false, c);
|
||||
}
|
||||
assert.match(ev("peerOk('msf','pni','ash').why"), /capacity|sold out|coming online/i);
|
||||
assert.equal(ev("peerOk('msf','pni','hou').ok"), true, 'Houston is fine');
|
||||
ev("ACT.pni({city:'ash',net:'msf',tier:1})");
|
||||
assert.equal(ev("S.pni.filter(p=>p.city==='ash').length"), 0);
|
||||
assert.equal(ev("peerOk('ggl','pni','ash').ok"), ev("R.demTo.ggl>=Math.round(NET.ggl.minPni)"), 'other networks are not affected');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('saves: PNIs on order survive, and garbage is repaired', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("S.pni.push({id:'x',city:'fra',net:'dtk',tier:0,g1:true,ready:S.day+30,up:{tier:'9',n:99,ready:'x'}},{id:'y',city:'fra',net:'nfx',tier:1,g1:true})");
|
||||
ev('const o=JSON.parse(JSON.stringify(S));sanitize(o);window.__o=o');
|
||||
assert.equal(ev("__o.pni.find(p=>p.id==='x').up.n"), ev('LAG_MAX'));
|
||||
assert.equal(ev("__o.pni.find(p=>p.id==='x').g1"), true);
|
||||
assert.equal(ev("__o.pni.find(p=>p.id==='y').g1"), undefined, 'only Doitsche Telekomm does 1G');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('now and then a route is sold out of a wave size, for a while, and asking again does not reroll it', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3");
|
||||
assert.equal(ev("S.day=10;!!soldOut('fra','ams',3,null)||!!soldOut('fra','ams',1,null)"), false, 'never in the first 90 days');
|
||||
// find a day when 400G is sold out between Frankfurt and Amsterdam
|
||||
const day = ev("(()=>{for(let d=90;d<20000;d++){S.day=d;if(soldOut('fra','ams',2,null))return d;}return -1;})()");
|
||||
assert.ok(day > 0, 'it happens');
|
||||
ev(`S.day=${day}`);
|
||||
const so = JSON.parse(ev("JSON.stringify(soldOut('fra','ams',2,null))"));
|
||||
assert.ok(so.until > day && so.until - day <= 90);
|
||||
assert.equal(ev(`S.day=${so.until - 1};!!soldOut('fra','ams',2,null)`), true, 'the same verdict for the whole window');
|
||||
ev(`S.day=${day}`);
|
||||
const share = ev("(()=>{let n=0;for(let d=90;d<20090;d++){S.day=d;if(soldOut('ams','fra',5,null))n++;}return n/20000;})()");
|
||||
assert.ok(share > 0.02 && share < 0.2, `rare, a bit more for big waves (${share})`);
|
||||
ev(`S.day=${day};UI.via=null;openLinkModal('fra','ams')`);
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /sold out for \d+ days/);
|
||||
const n = ev('S.links.length');
|
||||
ev('ACT.buildLink({tier:2})');
|
||||
assert.equal(ev('S.links.length'), n, 'no 400G today');
|
||||
assert.match(ev("document.getElementById('toasts').textContent"), /No 400G capacity on this route/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#201 a sold-out wave size cannot be reached by upgrading a smaller wave on the route', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;S.cash=1e9");
|
||||
const day = ev("(()=>{for(let d=90;d<20000;d++){S.day=d;if(soldOut('fra','ams',2,null)&&!soldOut('fra','ams',1,null))return d;}return -1;})()");
|
||||
assert.ok(day > 0, 'it happens');
|
||||
ev(`S.day=${day};S.links.push({id:'upw',a:'fra',b:'ams',kind:'wave',tier:1,km:400,sub:false,cable:null,mo:1,mult:1,trench:'upw',cut:0,day:0})`);
|
||||
const cash = ev('S.cash');
|
||||
ev("ACT.upLink({id:'upw',tier:2})");
|
||||
assert.equal(ev("S.links.find(l=>l.id==='upw').tier"), 1, 'still the old size');
|
||||
assert.equal(ev('S.cash'), cash, 'nothing charged');
|
||||
assert.match(ev("document.getElementById('toasts').textContent"), /No 400G capacity on this route/);
|
||||
// the link panel's button for that size is disabled and says why
|
||||
ev("UI.sel={type:'link',id:'upw'};renderPanel()");
|
||||
const b = ev(`(()=>{const b=[...document.querySelectorAll('[data-act=upLink]')].find(x=>JSON.parse(x.dataset.args).tier===2);return b?b.disabled+':'+b.textContent:''})()`);
|
||||
assert.match(b, /^true:.*sold out/i);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
42
tests/puzzle-monkey.test.js
Normal file
42
tests/puzzle-monkey.test.js
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
// The chaos monkey in every puzzle: it acts out the N-1 star on the map, and the stars never wait on it in tests.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const lay = (ev, a, b, via, div = 1) => ev(`if(!S.pops['${a}'])ACT.pzPop({city:'${a}'});ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:${div}});ACT.pzLink({tier:1});closeModal()`);
|
||||
const live = (ev) => ev('UI.drawnAt=performance.now()'); // as if the map were being drawn
|
||||
|
||||
test('a new star sets the monkey loose, then the stars show; skipping goes straight to them', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.pzStart({id:'bigboat'})");
|
||||
live(ev);
|
||||
lay(ev, 'fra', 'par', 'land'); lay(ev, 'fra', 'par', 'land');
|
||||
assert.ok(ev('pzEval().goal'), 'delivered');
|
||||
assert.ok(ev('!!UI.pzMk'), 'the monkey is reviewing the build');
|
||||
assert.ok(ev('!!UI.mk'), 'and it is on the map');
|
||||
assert.ok(ev("!!document.querySelector('#pzBox [data-act=pzMkSkip]')"), 'with a skip button');
|
||||
assert.equal(ev('pzEval().goal'), true, 'its cuts never change the stars');
|
||||
ev('ACT.pzMkSkip()');
|
||||
assert.equal(ev('UI.pzMk'), null);
|
||||
assert.ok(ev('S.links.every(l=>!l.cut)'), 'every tube whole again');
|
||||
assert.match(ev("document.getElementById('toasts').textContent+document.getElementById('modalCard').textContent"), /⭐/);
|
||||
assert.ok(ev("!!document.querySelector('#pzBox [data-act=pzMonkey]')"), 'and it can be let loose again');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the monkey snips each trench in turn, and an edit sends it away', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.pzStart({id:'bigboat'})");
|
||||
lay(ev, 'fra', 'par', 'land'); lay(ev, 'fra', 'par', 'land');
|
||||
ev("pzMonkey()");
|
||||
assert.equal(ev('UI.pzMk.units.length'), 2);
|
||||
assert.equal(ev('S.links.some(l=>l.cut)'), false, 'nothing cut while it runs');
|
||||
ev('pzMkHit()');
|
||||
assert.equal(ev('S.links.filter(l=>l.cut).length'), 1, 'one trench cut when it arrives');
|
||||
ev('pzMkStep()');
|
||||
assert.equal(ev('S.links.some(l=>l.cut)'), false, 'and whole again when it runs on');
|
||||
lay(ev, 'fra', 'par', 'land');
|
||||
assert.equal(ev('UI.pzMk'), null, 'a change to the build stops the review');
|
||||
assert.equal(ev('UI.mk'), null);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
556
tests/puzzles.test.js
Normal file
556
tests/puzzles.test.js
Normal file
|
|
@ -0,0 +1,556 @@
|
|||
// Puzzle mode (#190), with traffic: small builds that carry real flows, routed by the game's own compute(), with stars,
|
||||
// no clock, and a main save that is never touched.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
const SV = require('../scripts/lib/puzzle-solver');
|
||||
|
||||
/* Reference solutions, played through the player's own actions. A link is [a, b, route ('land' or a cable id), tier
|
||||
(0 = 10G, 1 = 100G, 2 = 400G), same]: a further overland link on a pair takes a diverse route, or with same = k
|
||||
goes into the k-th trench already there (added from the link panel). ['@rt', city, model, count] sets a POP's
|
||||
routers (RG index), ['@route', flow, 'fast'] sends a circuit the lowest-latency way. `one` earns the delivery star,
|
||||
`three` all three: the three-star ones are the cheapest builds the solver (scripts/lib/puzzle-solver.js) found. */
|
||||
const REF = {
|
||||
hello: { one: [['nyc', 'lon', 'grace', 0]], three: [['nyc', 'lon', 'grace', 0], ['nyc', 'lon', 'amitie', 0]] },
|
||||
eurotrip: { one: [['ams', 'lon', 'nshuttle', 1], ['ams', 'fra', 'land', 1]], three: [['ams', 'lon', 'concerto', 1], ['ams', 'lon', 'nshuttle', 1], ['ams', 'fra', 'land', 1], ['ams', 'fra', 'land', 1]] },
|
||||
bigboat: { one: [['fra', 'par', 'land', 1], ['fra', 'par', 'land', 1]], three: [['fra', 'par', 'land', 1], ['fra', 'par', 'land', 1], ['fra', 'par', 'land', 1]] },
|
||||
shining: { one: [['nyc', 'chi', 'land', 1], ['dal', 'sjc', 'land', 1], ['nyc', 'dal', 'land', 1]], three: [['nyc', 'chi', 'land', 1], ['nyc', 'chi', 'land', 1], ['chi', 'sjc', 'land', 1], ['dal', 'sjc', 'land', 1], ['nyc', 'dal', 'land', 1]] },
|
||||
downunder: { one: [['syd', 'mel', 'land', 1], ['syd', 'bne', 'land', 1], ['mel', 'adl', 'land', 1]], three: [['syd', 'mel', 'land', 1], ['syd', 'bne', 'land', 1], ['mel', 'adl', 'land', 1], ['bne', 'adl', 'land', 1]] },
|
||||
edgelord: { one: [['@rt', 'ams', 5, 1], ['@rt', 'lon', 5, 1], ['ams', 'lon', 'nshuttle', 2], ['ams', 'lon', 'circe', 1]], three: [['@rt', 'ams', 5, 1], ['@rt', 'lon', 5, 1], ['ams', 'lon', 'concerto', 2], ['ams', 'lon', 'nshuttle', 2], ['ams', 'lon', 'circe', 1]] },
|
||||
hubcap: { one: [['@rt', 'lon', 5, 1], ['lon', 'par', 'pasdc', 1], ['lon', 'ams', 'concerto', 1], ['lon', 'ams', 'circe', 1], ['lon', 'ams', 'nshuttle', 1], ['lon', 'par', 'pasdc', 1], ['ams', 'fra', 'land', 1], ['ams', 'fra', 'land', 1]], three: [['@rt', 'lon', 5, 1], ['lon', 'par', 'chn', 1], ['lon', 'par', 'pasdc', 1], ['ams', 'fra', 'land', 1], ['lon', 'ams', 'concerto', 1], ['lon', 'ams', 'circe', 1], ['lon', 'ams', 'nshuttle', 1], ['lon', 'par', 'chn', 1], ['lon', 'par', 'pasdc', 1], ['ams', 'fra', 'land', 1], ['ams', 'fra', 'land', 1], ['lon', 'ams', 'uly', 1]] },
|
||||
flash: { one: [['nyc', 'lon', 'hibx', 1]], three: [['nyc', 'lon', 'grace', 1], ['nyc', 'lon', 'hibx', 0]] },
|
||||
baltic: { one: [['fra', 'hel', 'clion', 1], ['tll', 'hel', 'land', 1], ['@route', 1, 'fast']], three: [['fra', 'hel', 'clion', 1], ['tll', 'hel', 'land', 1], ['fra', 'tll', 'land', 1], ['@route', 1, 'fast']] },
|
||||
fjord: { one: [['par', 'lon', 'pasdc', 1], ['svg', 'lon', 'tampn', 1], ['@route', 1, 'fast']], three: [['par', 'svg', 'land', 1], ['par', 'lon', 'pasdc', 1], ['svg', 'lon', 'tampn', 1], ['@route', 1, 'fast']] },
|
||||
braces: { one: [['nyc', 'dub', 'havf', 1], ['lon', 'dub', 'celtix', 1]], three: [['nyc', 'lon', 'grace', 1], ['nyc', 'dub', 'havf', 1], ['lon', 'dub', 'celtix', 1]] },
|
||||
sharks: { one: [['lis', 'mad', 'land', 1], ['lis', 'bcn', 'land', 1], ['par', 'mil', 'land', 1], ['par', 'mrs', 'land', 1], ['bcn', 'mrs', 'land', 1]], three: [['lis', 'mad', 'land', 1], ['lis', 'mad', 'land', 1], ['lis', 'bcn', 'land', 1], ['mad', 'bcn', 'land', 1], ['par', 'mil', 'land', 1], ['par', 'mrs', 'land', 1], ['mil', 'bcn', 'land', 1], ['bcn', 'mrs', 'land', 1]] },
|
||||
nofra: { one: [['ams', 'dus', 'land', 1], ['ams', 'dus', 'land', 1], ['ber', 'ham', 'land', 1], ['muc', 'zrh', 'land', 1], ['muc', 'dus', 'land', 1], ['ham', 'dus', 'land', 1]], three: [['ams', 'ham', 'land', 1], ['ams', 'dus', 'land', 1], ['ams', 'dus', 'land', 1], ['ber', 'ham', 'land', 1], ['ber', 'ham', 'land', 1], ['muc', 'zrh', 'land', 1], ['muc', 'dus', 'land', 1], ['zrh', 'dus', 'land', 1], ['ham', 'dus', 'land', 1]] },
|
||||
fire: { one: [['tok', 'hkg', 'adc', 1], ['hkg', 'sin', 'land', 1], ['sin', 'syd', 'indigo', 1], ['syd', 'tok', 'guam', 1]], three: [['tok', 'hkg', 'adc', 1], ['hkg', 'sin', 'land', 1], ['sin', 'syd', 'indigo', 1], ['syd', 'tok', 'guam', 1]] },
|
||||
suez: { one: [['fra', 'mrs', 'land', 1], ['sin', 'mrs', 'peace', 1]], three: [['fra', 'mrs', 'land', 1], ['fra', 'mrs', 'land', 0], ['sin', 'mrs', 'peace', 1], ['sin', 'bom', 'land', 0], ['mrs', 'bom', 'twoaf', 0]] },
|
||||
kiwi: { one: [['sea', 'lax', 'land', 1], ['akl', 'syd', 'tasman', 1], ['akl', 'hnl', 'hwk', 1], ['hnl', 'lax', 'seaus', 1]], three: [['sea', 'hnl', 'hwk', 1], ['sea', 'lax', 'land', 1], ['akl', 'syd', 'scx', 1], ['akl', 'syd', 'tasman', 1], ['akl', 'hnl', 'hwk', 1], ['akl', 'suv', 'scx', 1], ['hnl', 'suv', 'scx', 1], ['hnl', 'lax', 'seaus', 1]] },
|
||||
samba: { one: [['mia', 'for', 'monet', 1], ['sao', 'rio', 'land', 1], ['sao', 'for', 'land', 1]], three: [['mia', 'for', 'monet', 1], ['mia', 'for', 'sam1', 1], ['sao', 'rio', 'land', 1], ['sao', 'for', 'land', 1], ['rio', 'for', 'land', 1]] },
|
||||
ports: { one: [['@rt', 'zrh', 4, 1], ['zrh', 'mil', 'land', 0], ['zrh', 'mil', 'land', 0], ['zrh', 'muc', 'land', 0], ['zrh', 'muc', 'land', 0], ['zrh', 'fra', 'land', 0], ['zrh', 'fra', 'land', 0], ['zrh', 'par', 'land', 0], ['zrh', 'par', 'land', 0], ['zrh', 'vie', 'land', 0], ['zrh', 'vie', 'land', 0], ['zrh', 'prg', 'land', 0], ['zrh', 'prg', 'land', 0]], three: [['@rt', 'zrh', 5, 1], ['zrh', 'mil', 'land', 0], ['zrh', 'mil', 'land', 0], ['zrh', 'mil', 'land', 0], ['zrh', 'muc', 'land', 0], ['zrh', 'muc', 'land', 0], ['zrh', 'muc', 'land', 0], ['zrh', 'fra', 'land', 0], ['zrh', 'fra', 'land', 0], ['zrh', 'fra', 'land', 0], ['zrh', 'par', 'land', 0], ['zrh', 'par', 'land', 0], ['zrh', 'par', 'land', 0], ['zrh', 'vie', 'land', 0], ['zrh', 'vie', 'land', 0], ['zrh', 'vie', 'land', 0], ['zrh', 'prg', 'land', 0], ['zrh', 'prg', 'land', 0], ['zrh', 'prg', 'land', 0]] },
|
||||
};
|
||||
|
||||
function build(ev, steps) {
|
||||
for (const s of steps) {
|
||||
if (s[0] === '@rt') { const [, c, g, n] = s; if (!ev(`!!S.pops['${c}']`)) ev(`ACT.pzPop({city:'${c}'})`); if (g) ev(`ACT.pzRtModel({city:'${c}',g:${g}})`); for (let i = 1; i < n; i++) ev(`ACT.pzRtAdd({city:'${c}'})`); continue; }
|
||||
if (s[0] === '@route') { ev(`ACT.pzRoute({i:${s[1]},m:'${s[2]}'})`); continue; }
|
||||
const [a, b, via, tier, same] = s;
|
||||
if (!ev(`!!S.pops['${a}']`)) ev(`ACT.pzPop({city:'${a}'})`);
|
||||
if (same) ev(`(()=>{const ls=S.links.filter(l=>edgeKey(l)===edgeKey({a:'${a}',b:'${b}'})&&!l.cable),ts=[...new Set(ls.map(pzUnit))],l=ls.find(x=>pzUnit(x)===ts[${same - 1}]);ACT.pzAddPar({id:l.id,div:0});ACT.pzLink({tier:${tier}})})()`);
|
||||
else ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:${tier || 0}})`);
|
||||
}
|
||||
ev('closeModal()');
|
||||
}
|
||||
const evalP = (ev) => JSON.parse(ev('JSON.stringify(pzEval())'));
|
||||
const links = (steps) => steps.filter((s) => s[0] !== '@rt');
|
||||
|
||||
test('puzzle data: every puzzle is valid, carries traffic, and its references earn their stars through the real routing', () => {
|
||||
const { ev, errors } = load();
|
||||
const ids = JSON.parse(ev('JSON.stringify(PZ.map(p=>p.id))'));
|
||||
assert.ok(ids.length >= 16 && ids.length <= 20, '16 to 20 puzzles');
|
||||
assert.equal(new Set(ids).size, ids.length, 'ids are unique');
|
||||
assert.deepEqual(Object.keys(REF).sort(), ids.slice().sort(), 'every puzzle has a reference solution');
|
||||
assert.ok(ev("PZ.every(p=>PZ_PACKS.some(k=>k.id===p.pack)&&p.n&&p.j&&p.dem.length>=1&&pzCities(p).length>=2&&pzCities(p).length<=7&&[...pzCities(p),...(p.via||[]),...(p.avoid||[])].every(pzCityOk))"), 'cities exist and are playable');
|
||||
assert.ok(ev("PZ.every(p=>p.dem.every(f=>f.g>0&&(f.t==='eye'?(p.src||[]).length>0&&!p.src.includes(f.a):f.t==='l2'&&f.a!==f.b)))"), 'eyeballs have an origin, circuits two ends');
|
||||
assert.ok(ev("PZ.every(p=>!p.budget||(p.budget>=100000&&p.budget<=5e6))"), 'budgets are sane');
|
||||
assert.ok(ev("PZ_PACKS[0].need===0&&PZ_PACKS.every((k,i)=>!i||k.need>PZ_PACKS[i-1].need)"), 'packs unlock in order');
|
||||
assert.ok(ev("PZ_PACKS.every(k=>PZ.filter(p=>p.pack===k.id).length>=3)"), 'every pack has at least three puzzles');
|
||||
assert.ok(ev("PZ.filter(p=>p.pack==='hello'&&!p.budget).length>=2"), 'the first puzzles give the budget star away');
|
||||
for (const id of ids) {
|
||||
ev(`pzBegin(pzDef('${id}'))`);
|
||||
build(ev, REF[id].one);
|
||||
let e = evalP(ev);
|
||||
assert.ok(e.goal, `${id}: the one-star reference delivers everything (${JSON.stringify(e.flows.map((x) => [x.g, x.ms]))})`);
|
||||
ev('ACT.pzReset({})');
|
||||
assert.equal(evalP(ev).stars, 0, `${id}: reset clears it`);
|
||||
build(ev, REF[id].three);
|
||||
e = evalP(ev);
|
||||
assert.equal(e.stars, 3, `${id}: three stars (spend ${e.spend} of ${ev('S.pz.budget')}, n1 ${e.n1}, worst cut ${JSON.stringify(e.worst)})`);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('budgets follow the teaching curve, and each 3-star reference is the cheapest build nearby', () => {
|
||||
const { ev, errors } = load();
|
||||
SV.install(ev);
|
||||
// Slack over the cheapest 3-star build found: roomy first, tight at the end. Traffic Cops is tight on purpose: the
|
||||
// routing trick (a circuit on the lowest-latency path) is what brings it under budget.
|
||||
const SLACK = { hello: [0.15, 0.22], rodeo: [0.09, 0.13], cops: [0.03, 0.06], n1: [0.05, 0.08], final: [0.04, 0.07] };
|
||||
const rows = JSON.parse(ev('JSON.stringify(PZ.filter(p=>p.budget).map(p=>({id:p.id,pack:p.pack,budget:p.budget})))'));
|
||||
for (const { id, pack, budget } of rows) {
|
||||
ev(`pzBegin(pzDef('${id}'))`);
|
||||
build(ev, REF[id].three);
|
||||
const e = evalP(ev);
|
||||
assert.equal(e.stars, 3, id);
|
||||
// The routers in the reference are the cheapest that carry it: the solver prices the same build the same.
|
||||
const L = links(REF[id].three), j = SV.judge(ev, L);
|
||||
assert.ok(j.three && Math.abs(j.spend - e.spend) < 1, `${id}: solver ${j.spend} vs game ${e.spend}`);
|
||||
// No single change (drop a link, shrink one, move it to another route or trench) keeps three stars for less.
|
||||
const r = SV.improve(ev, L);
|
||||
assert.ok(r.spend >= e.spend - 1, `${id}: ${JSON.stringify(r.links)} is cheaper (${r.spend})`);
|
||||
const slack = budget / e.spend - 1, [lo, hi] = SLACK[pack];
|
||||
assert.ok(slack >= lo && slack <= hi, `${id}: ${(slack * 100).toFixed(1)}% slack, want ${lo * 100}-${hi * 100}%`);
|
||||
}
|
||||
assert.match(ev("PZ_PACKS[0].d"), /Roomy budgets/, 'the first pack does not promise "no budget"');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('stars come from traffic: capacity, latency caps, best effort and N-1 under load', () => {
|
||||
const { ev, errors } = load();
|
||||
// Connected is not delivered: a 10G wave for 30G of London eyeballs gets 10G there.
|
||||
ev("pzBegin(pzDef('eurotrip'))");
|
||||
build(ev, [['ams', 'lon', 'nshuttle', 0], ['ams', 'fra', 'land', 1]]);
|
||||
let e = evalP(ev);
|
||||
assert.ok(!e.goal && Math.abs(e.flows[0].g - 10) < 0.1, `10G of 30G (${e.flows[0].g})`);
|
||||
assert.match(ev("document.getElementById('pzBox').textContent"), /Eyeballs in London(9\.\d|10\.0) Gbps \/ 30\.0 Gbps/);
|
||||
ev("ACT.pzTier({id:S.links[0].id,tier:1})");
|
||||
assert.ok(evalP(ev).goal, 'a 100G wave carries it');
|
||||
// N-1 under load: two trenches into Paris are connected after a cut, but one 100G wave cannot carry 150G.
|
||||
ev("pzBegin(pzDef('bigboat'))");
|
||||
build(ev, [['fra', 'par', 'land', 1], ['fra', 'par', 'land', 1, 1], ['fra', 'par', 'land', 1]]);
|
||||
e = evalP(ev);
|
||||
assert.ok(e.goal && !e.n1, 'still connected after a cut, but short');
|
||||
assert.equal(Math.round(e.worst.g), 50, 'cutting the trench with two waves leaves 100G for 150G: 50G drop');
|
||||
assert.match(ev("document.getElementById('pzBox').textContent"), /A cut on Frankfurt ⇄ Paris drops 50\.\d Gbps/);
|
||||
build(ev, [['fra', 'par', 'land', 1, 2]]);
|
||||
assert.ok(evalP(ev).n1, 'two waves in each trench: either one carries Paris alone');
|
||||
// A latency cap: Grace Hopscotch is too slow for the traders; the eyeballs are best effort and may drop on a cut.
|
||||
ev("pzBegin(pzDef('flash'))");
|
||||
build(ev, [['nyc', 'lon', 'grace', 1]]);
|
||||
e = evalP(ev);
|
||||
assert.ok(!e.goal && e.flows[0].full && !e.flows[0].fast, 'all of the circuit, but at 29 ms');
|
||||
build(ev, [['nyc', 'lon', 'hibx', 0]]);
|
||||
e = evalP(ev);
|
||||
assert.equal(e.stars, 3, 'the fast cable for the circuit; when the big one is cut, only best effort drops');
|
||||
// A circuit follows the metrics unless told otherwise: the road to Tallinn is shorter, the light via Helsinki faster.
|
||||
ev("pzBegin(pzDef('baltic'))");
|
||||
build(ev, links(REF.baltic.three).filter((s) => s[0] !== '@route'));
|
||||
e = evalP(ev);
|
||||
assert.ok(!e.goal && e.flows[1].ms > 8.8, `the metric path is too slow (${e.flows[1].ms})`);
|
||||
assert.ok(ev("!!document.querySelector('#pzBox [data-act=pzRoute]')"), 'the card has the circuit\'s route switch');
|
||||
ev("document.querySelector('#pzBox [data-act=pzRoute][data-args*=fast]').click()");
|
||||
e = evalP(ev);
|
||||
assert.ok(e.goal && e.flows[1].ms <= 8.8, 'lowest latency goes via Helsinki');
|
||||
ev('ACT.pzUndo({})');
|
||||
assert.equal(ev("S.biz[0].route"), 'normal', 'undo takes the route back');
|
||||
// The main game's metric control works in a puzzle and moves the traffic: Backup only on the road pushes the
|
||||
// eyeballs through Helsinki too.
|
||||
ev("ACT.pzRoute({i:1,m:'fast'});ACT.selLink({id:S.links.find(l=>edgeKey(l)==='fra|tll').id})");
|
||||
assert.match(ev("document.getElementById('panelBody').textContent"), /Routing metric/);
|
||||
ev("ACT.setMetric({id:S.links.find(l=>edgeKey(l)==='fra|tll').id,v:'backup'})");
|
||||
assert.ok(ev("(R.load[S.links.find(l=>edgeKey(l)==='fra|tll').id]||0)<0.01"), 'nothing on a backup-only link while the others are up');
|
||||
ev('ACT.pzUndo({})');
|
||||
assert.ok(ev("!S.pairMet['fra|tll']"), 'undo takes the metric back');
|
||||
// Over budget loses the second star only.
|
||||
ev("pzBegin(pzDef('braces'))");build(ev, REF.braces.three);
|
||||
assert.equal(evalP(ev).stars, 3);
|
||||
ev('S.pz.budget=1000');
|
||||
assert.equal(evalP(ev).stars, 2);
|
||||
// A cable fails as a whole: two waves on one cable are one cut.
|
||||
ev("pzBegin(pzDef('kiwi'))");
|
||||
build(ev, [['akl', 'syd', 'scx', 1], ['akl', 'suv', 'scx', 1]]);
|
||||
assert.equal(ev("new Set(S.links.map(pzUnit)).size"), 1, 'one cable, one failure unit');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('parallel links say how many they are and where they run; diversity from the link panel', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("pzBegin(pzDef('bigboat'))");
|
||||
build(ev, [['fra', 'par', 'land', 1]]);
|
||||
const id = ev('S.links[0].id');
|
||||
ev(`ACT.selLink({id:'${id}'})`);
|
||||
let panel = ev("document.getElementById('panelBody').textContent");
|
||||
assert.match(panel, /Add another link on this pair/);
|
||||
// Same trench from the panel: no surcharge, one failure unit, one line on the map labelled 2×100G.
|
||||
ev(`ACT.pzAddPar({id:'${id}',div:0})`);
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /Already on this pair: 1×100G · trench 1/);
|
||||
ev('ACT.pzLink({tier:1})');
|
||||
assert.equal(ev("new Set(S.links.map(pzUnit)).size"), 1);
|
||||
assert.equal(ev('S.links[1].mo'), ev('S.links[0].mo'));
|
||||
assert.equal(ev("pzLinkLab(S.links,S.links,R.load[S.links[0].id]+R.load[S.links[1].id],200)"), '2×100G · 75%');
|
||||
assert.equal(ev("groupLabel(linkGroups()[0],linkGroups()[0])"), '2×100G', 'the map draws one line for the trench, labelled with its count');
|
||||
// A diverse one from the panel: its own trench, 40% dearer, its own line.
|
||||
ev(`ACT.pzAddPar({id:'${id}',div:1});ACT.pzLink({tier:1})`);
|
||||
assert.equal(ev("new Set(S.links.map(pzUnit)).size"), 2);
|
||||
assert.equal(ev('S.links[2].mo'), ev('Math.round(S.links[0].mo*DIVERSE)'));
|
||||
assert.equal(ev('linkGroups().length'), 2);
|
||||
ev(`ACT.selLink({id:'${id}'})`);
|
||||
panel = ev("document.getElementById('panelBody').textContent");
|
||||
assert.match(panel, /3 links on this pair: 3×100G/);
|
||||
assert.match(panel, /trench 1/);
|
||||
assert.match(panel, /trench 2/);
|
||||
// Selecting a city lights up every pair it has links on, and its panel lists them with their loads.
|
||||
ev("selectCity('par')");
|
||||
assert.ok(ev('pzLinkHot(S.links)'));
|
||||
panel = ev("document.getElementById('panelBody').textContent");
|
||||
assert.match(panel, /Frankfurt · 3×100G150 Gbps \/ 300 Gbps/);
|
||||
// A subsea link: "a different route" picks another cable.
|
||||
ev("pzBegin(pzDef('hello'))");build(ev, [['nyc', 'lon', 'grace', 0]]);
|
||||
ev("ACT.pzAddPar({id:S.links[0].id,div:1})");
|
||||
assert.notEqual(ev('UI.pzVia'), 'grace');
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /Already on this pair: 1×10G/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('routers in a puzzle: ports, wave sizes and capacity as in the main game, priced into the budget', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("pzBegin(pzDef('edgelord'))");
|
||||
build(ev, [['ams', 'lon', 'nshuttle', 0]]);
|
||||
// A Rusty Router lights 100G at most.
|
||||
ev("ACT.pzLinkTo({a:'ams',b:'lon'});ACT.pzVia({v:'concerto'})");
|
||||
assert.match(ev("document.querySelector('#modalCard .tierbtn[data-args*=\"2\"]').textContent"), /needs 400G routers/);
|
||||
assert.equal(ev("document.querySelector('#modalCard .tierbtn[data-args*=\"2\"]').disabled"), true);
|
||||
ev('closeModal()');
|
||||
// Eight ports: the ninth wave is refused, a second router makes room, and it is in the bill.
|
||||
for (let i = 0; i < 7; i++) ev("ACT.pzLinkTo({a:'ams',b:'lon'});ACT.pzVia({v:'nshuttle'});ACT.pzLink({tier:0})");
|
||||
assert.equal(ev('S.links.length'), 8);
|
||||
ev("ACT.pzLinkTo({a:'ams',b:'lon'})");
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /No free router ports in Amsterdam, London/);
|
||||
ev("ACT.pzVia({v:'nshuttle'});ACT.pzLink({tier:0})");
|
||||
assert.equal(ev('S.links.length'), 8, 'no port, no wave');
|
||||
const sp0 = evalP(ev).spend;
|
||||
ev("ACT.pzRtAdd({city:'ams'});ACT.pzRtAdd({city:'lon'})");
|
||||
assert.equal(evalP(ev).spend - sp0, ev('2*pzRtCost(0,2)'), 'two second routers, priced as the main game prices them');
|
||||
ev("ACT.pzLinkTo({a:'ams',b:'lon'});ACT.pzVia({v:'nshuttle'});ACT.pzLink({tier:0})");
|
||||
assert.equal(ev('S.links.length'), 9);
|
||||
ev("ACT.pzRtRm({city:'ams'})");
|
||||
assert.equal(ev('S.pops.ams.routers'), 2, 'cannot drop a router whose ports are in use');
|
||||
// The city panel shows the POP: model, load against capacity, ports.
|
||||
ev("selectCity('lon')");
|
||||
const panel = ev("document.getElementById('panelBody').textContent");
|
||||
assert.match(panel, /2 × Rusty Router 9000/);
|
||||
assert.match(panel, /Ports9 of 16 used/);
|
||||
assert.match(panel, /Router load90\.0 Gbps \/ 800 Gbps/);
|
||||
// Capacity: a Rusty Router moves 400G. Three 400G waves on Sonic routers bring 1.2T, but a Rusty-sized POP would
|
||||
// stop at 400G of the 500G London wants.
|
||||
ev("pzBegin(pzDef('edgelord'))");
|
||||
build(ev, [['@rt', 'ams', 5, 1], ['@rt', 'lon', 5, 1], ['ams', 'lon', 'concerto', 2], ['ams', 'lon', 'nshuttle', 2]]);
|
||||
assert.equal(Math.round(evalP(ev).flows[0].g), 500);
|
||||
ev("ACT.pzRtModel({city:'lon',g:0})");
|
||||
assert.equal(ev('S.pops.lon.rgen'), 5, 'a Rusty Router cannot take a 400G wave: the swap is refused');
|
||||
ev("S.pops.lon.rgen=4;UI.pzEv=null");// a Mikrowtik moves 300G (set directly: it refuses 400G waves too)
|
||||
assert.ok(Math.abs(evalP(ev).flows[0].g - 300) < 5, 'the router is the bottleneck');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the whole world is open: an off-plan city can get a POP and links, and it counts in the budget', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("pzBegin(pzDef('bigboat'))");
|
||||
assert.equal(ev("pzKind('bru')"), 'off');
|
||||
ev("selectCity('bru')");
|
||||
assert.match(ev("document.getElementById('panelBody').textContent"), /Not in the plan/);
|
||||
ev("ACT.pzPop({city:'bru'})");
|
||||
assert.ok(ev('!!S.pops.bru'));
|
||||
const sp = evalP(ev).spend;
|
||||
assert.equal(sp, ev("pzPopCost('bru')"));
|
||||
ev("ACT.pzLinkTo({a:'bru',b:'par'});ACT.pzVia({v:'land'});ACT.pzLink({tier:1})");
|
||||
ev("ACT.pzLinkTo({a:'bru',b:'fra'});ACT.pzVia({v:'land'});ACT.pzLink({tier:1})");
|
||||
const e = evalP(ev);
|
||||
assert.ok(e.spend > sp && Math.round(e.flows[0].g) === 100, 'Paris gets 100G through Brussels');
|
||||
assert.equal(ev("pzKind('pek')"), null, 'cities that need a licence stay out');
|
||||
ev("pzBegin(pzDef('nofra'));ACT.pzPop({city:'fra'})");
|
||||
assert.equal(ev('!!S.pops.fra'), false, 'a city to avoid stays off limits');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('determinism and speed: the same build always gets the same stars, fast enough on the biggest puzzle', () => {
|
||||
const { ev, errors } = load();
|
||||
const run = (id) => { ev(`pzBegin(pzDef('${id}'))`); build(ev, REF[id].three); ev('UI.pzEv=null'); const a = ev('JSON.stringify(pzEval())'); ev('UI.pzEv=null'); return [a, ev('JSON.stringify(pzEval())')]; };
|
||||
const [a, b] = run('kiwi'), [c] = run('kiwi');
|
||||
assert.equal(a, b, 'twice in a row');
|
||||
assert.equal(a, c, 'and from scratch');
|
||||
// The biggest puzzle by failure units: one full evaluation (routing plus every single cut).
|
||||
const big = ev("PZ.map(p=>p.id).sort()[0]") && JSON.parse(ev('JSON.stringify(PZ.map(p=>p.id))')).map((id) => { ev(`pzBegin(pzDef('${id}'))`); build(ev, REF[id].three); return [id, ev('new Set(S.links.map(pzUnit)).size')]; }).sort((x, y) => y[1] - x[1])[0];
|
||||
ev(`pzBegin(pzDef('${big[0]}'))`); build(ev, REF[big[0]].three);
|
||||
for (let i = 0; i < 3; i++) ev('UI.pzEv=null;pzEval()');
|
||||
const ms = ev('(()=>{const t=performance.now();for(let i=0;i<5;i++){UI.pzEv=null;pzEval();}return (performance.now()-t)/5})()');
|
||||
console.log(`# star evaluation on ${big[0]} (${big[1]} failure units): ${ms.toFixed(1)} ms`);
|
||||
assert.ok(ms < 150, `${big[0]}: ${ms.toFixed(1)} ms`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('progress: the puzzle set with traffic starts the stars again once, with the old ones framed', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("localStorage.setItem('sot-puzzles',JSON.stringify({s:{hello:{st:3,sp:1},eurotrip:{st:2},gone:{st:3}},wk:{'2026-W40':{st:3,sp:9}},streak:{last:'2026-W40',n:2,best:4}}))");
|
||||
let p = JSON.parse(ev('JSON.stringify(pzLoad())'));
|
||||
assert.deepEqual(p.s, {}, 'old stars do not count in the new set');
|
||||
assert.equal(p.old, 8);
|
||||
assert.deepEqual(p.wk, { '2026-W40': { st: 3, sp: 9 } }, 'weekly results stay');
|
||||
assert.equal(p.streak.best, 4, 'and so does the streak');
|
||||
ev('ACT.puzzleMenu({})');
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /Puzzles got traffic!.*Your old 8 ⭐ are framed on the wall/);
|
||||
ev('closeModal();ACT.puzzleMenu({})');
|
||||
assert.doesNotMatch(ev("document.getElementById('modalCard').textContent"), /Puzzles got traffic!/, 'the note shows once');
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /Framed on the wall: 8 ⭐/);
|
||||
// New stars are kept under the new set.
|
||||
ev("pzBegin(pzDef('hello'))");build(ev, REF.hello.three);
|
||||
p = JSON.parse(ev("localStorage.getItem('sot-puzzles')"));
|
||||
assert.equal(p.set, 2);
|
||||
assert.equal(p.s.hello.st, 3);
|
||||
assert.equal(JSON.parse(ev('JSON.stringify(pzLoad())')).old, 8);
|
||||
// Bad data is ignored.
|
||||
ev("localStorage.setItem('sot-puzzles',JSON.stringify({set:2,s:{hello:{st:99,sp:'x'},nope:{st:3}},old:'<b>',wk:{bad:{st:3}},streak:{n:-4,last:'<b>'}}))");
|
||||
p = JSON.parse(ev('JSON.stringify(pzLoad())'));
|
||||
assert.deepEqual(p.s, { hello: { st: 3, sp: null } });
|
||||
assert.equal(p.old, null);
|
||||
assert.deepEqual(p.wk, {});
|
||||
assert.deepEqual(p.streak, { last: null, n: 0, best: 0 });
|
||||
ev("localStorage.setItem('sot-puzzles','{nope')");
|
||||
assert.equal(ev('pzStarsTotal(pzLoad())'), 0);
|
||||
// Packs unlock by the new stars.
|
||||
ev("localStorage.removeItem('sot-puzzles')");
|
||||
assert.equal(ev("pzPackOpen('rodeo')"), false);
|
||||
ev("ACT.pzStart({id:'edgelord'})");
|
||||
assert.notEqual(ev('S.pz.id'), 'edgelord', 'a locked puzzle does not start');
|
||||
ev("localStorage.setItem('sot-puzzles',JSON.stringify({set:2,s:{hello:{st:3},eurotrip:{st:3},bigboat:{st:2},shining:{st:2}}}))");
|
||||
assert.equal(ev("pzPackOpen('rodeo')"), true, '10 stars open pack 2');
|
||||
ev('ACT.puzzleMenu({})');
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /Next pack, Traffic Cops, unlocks at 18/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('results card: stars, the next puzzle, a retry, a share line and stars left in the pack', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('eurotrip'))");
|
||||
build(ev, REF.eurotrip.one);
|
||||
assert.ok(ev("$('modal').hidden||!document.querySelector('#modalCard .pzres')"), 'two stars: no results card, play goes on');
|
||||
assert.match(ev("document.getElementById('toasts').textContent"), /One chaos monkey away/, 'a cheer with the next step instead');
|
||||
assert.ok(ev("!!document.querySelector('[data-act=pzFinish]')"), 'and a Finish button on the card');
|
||||
ev("document.querySelector('[data-act=pzFinish]').click()");
|
||||
let card = ev("document.getElementById('modalCard').textContent");
|
||||
assert.match(card, /Your stars so far/);
|
||||
assert.equal(evalP(ev).stars, 2, 'delivered, and the budget star is on the house');
|
||||
assert.match(card, /One chaos monkey away/);
|
||||
assert.match(card, /13 ⭐ left in this pack/);
|
||||
assert.ok(ev("!!document.querySelector('#modalCard [data-act=pzRetry]')"));
|
||||
build(ev, [['ams', 'lon', 'concerto', 1], ['ams', 'fra', 'land', 1]]);
|
||||
card = ev("document.getElementById('modalCard').textContent");
|
||||
assert.match(card, /A chaos monkey walks into your network/);
|
||||
assert.equal(ev("document.querySelectorAll('#modalCard .pzbig.on').length"), 3);
|
||||
assert.ok(ev("document.querySelector('#modalCard .btns.cta').classList.contains('pzdone')"));
|
||||
assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /Next puzzle →/);
|
||||
assert.equal(ev("document.querySelector('#modalCard [data-act=pzRetry]')"), null, 'no retry after three stars');
|
||||
assert.match(ev('pzShareText(pzEval())'), /^Series of Tubes puzzle Euro Trip ⭐⭐⭐ \$[\d.]+[kM] · seriesoftub\.es$/);
|
||||
// The last puzzle points back to the list.
|
||||
ev("localStorage.setItem('sot-puzzles',JSON.stringify({set:2,s:Object.fromEntries(PZ.map(p=>[p.id,{st:3}]))}));pzBegin(pzDef('samba'))");
|
||||
build(ev, REF.samba.three);
|
||||
assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /More puzzles/);
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /Every star in this pack is yours/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('best spend: kept for the best star count, and a cheaper build at the same stars counts', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('braces'))");
|
||||
const rec = () => JSON.parse(ev("JSON.stringify(pzLoad().s.braces||null)"));
|
||||
build(ev, REF.braces.three);
|
||||
const three = evalP(ev);
|
||||
assert.deepEqual(rec(), { st: 3, sp: three.spend });
|
||||
ev('S.pz.budget=1e7;ACT.pzTier({id:S.links[0].id,tier:2})');
|
||||
assert.equal(ev('S.links[0].tier'), 1, 'a 400G wave needs 400G routers: refused');
|
||||
ev("ACT.pzRtAdd({city:'nyc'})");
|
||||
assert.equal(evalP(ev).stars, 3);
|
||||
assert.deepEqual(rec(), { st: 3, sp: three.spend }, 'a dearer 3-star build does not replace it');
|
||||
ev("ACT.pzRmLink({id:S.links[0].id})");
|
||||
assert.deepEqual(rec(), { st: 3, sp: three.spend }, 'fewer stars never overwrite more');
|
||||
ev('ACT.puzzleMenu({})');
|
||||
assert.ok(ev("document.getElementById('modalCard').textContent").includes('best ' + ev(`fmt$(${three.spend})`)));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('weekly puzzle (seeded stand-in): stable per week, carries traffic, its reference ring earns three stars, streak', () => {
|
||||
const { ev, errors } = load();
|
||||
const a = ev("JSON.stringify(pzWeekly(new Date(2026,9,28)))"), b = ev("JSON.stringify(pzWeekly(new Date(2026,10,1)))"), c = ev("JSON.stringify(pzWeekly(new Date(2026,10,2)))");
|
||||
assert.equal(a, b, 'same week, same puzzle');
|
||||
assert.notEqual(a, c, 'next week, a new one');
|
||||
const w = JSON.parse(a);
|
||||
assert.equal(w.key, '2026-W44');
|
||||
assert.ok(w.cities.length >= 4 && w.dem.length === w.cities.length - 1 && w.src[0] === w.cities[0]);
|
||||
for (let i = 0; i < 400; i += 28) {
|
||||
const wi = JSON.parse(ev(`JSON.stringify(pzWeekly(new Date(2026,0,1+${i})))`));
|
||||
ev(`pzBegin(pzWeekly(new Date(2026,0,1+${i})))`);
|
||||
build(ev, wi.ref.map((x, j) => [x, wi.ref[(j + 1) % wi.ref.length], wi.refVia[j], 0]));
|
||||
assert.equal(evalP(ev).stars, 3, `week +${i}`);
|
||||
}
|
||||
ev("localStorage.removeItem('sot-puzzles');pzBegin(pzWeekly(new Date(2026,9,28)))");
|
||||
build(ev, w.ref.map((x, j) => [x, w.ref[(j + 1) % w.ref.length], w.refVia[j], 0]));
|
||||
assert.match(ev('pzShareText(pzEval())'), /^Series of Tubes puzzle 2026-W44 ⭐⭐⭐ \$[\d.]+[kM] · seriesoftub\.es$/);
|
||||
assert.equal(ev("JSON.parse(localStorage.getItem('sot-puzzles')).streak.n"), 1);
|
||||
ev("const p=pzLoad();pzStreak(p,'2026-W45');pzStreak(p,'2026-W45');pzStreak(p,'2026-W46');window.__p=p");
|
||||
assert.equal(ev('__p.streak.n'), 3);
|
||||
ev("pzStreak(__p,'2026-W49')");
|
||||
assert.equal(ev('__p.streak.n'), 1);
|
||||
assert.equal(ev('__p.streak.best'), 3);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('puzzle HUD and panels fit a 360 px phone, portrait and landscape', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'))");
|
||||
ev("pzBegin(pzDef('baltic'))");
|
||||
assert.equal(ev("document.getElementById('tabbar').hidden"), true);
|
||||
assert.equal(ev("document.getElementById('pzBox').hidden"), false);
|
||||
const box = ev("document.getElementById('pzBox').textContent");
|
||||
assert.match(box, /Eyeballs in Tallinn/);
|
||||
assert.match(box, /Frankfurt ⇄ Tallinn circuit/);
|
||||
assert.match(box, /Content lives in Frankfurt/);
|
||||
ev("selectCity('fra')");
|
||||
assert.match(ev("document.getElementById('panelBody').textContent"), /Open a POP/);
|
||||
ev("document.querySelector('#panelBody [data-act=pzPop]').click()");
|
||||
assert.match(ev("document.getElementById('panelBody').textContent"), /Your POP[\s\S]*Router load[\s\S]*Ports[\s\S]*Router model/);
|
||||
ev("pzLinkModal('fra','tll')");
|
||||
assert.equal(ev("document.querySelectorAll('#modalCard .tierbtn').length"), 4, 'four sizes');
|
||||
ev("closeModal();innerWidth=740;innerHeight=360;dispatchEvent(new Event('resize'));renderAll()");
|
||||
assert.equal(ev("document.getElementById('pzBox').hidden"), false, 'landscape too');
|
||||
// jsdom has no layout: the phone rules keep 40 px targets and pin the action row.
|
||||
const rules = JSON.parse(ev(`JSON.stringify([...document.styleSheets].flatMap(s=>[...s.cssRules]).filter(r=>r.media&&/max-width: ?760px/.test(r.media.mediaText))
|
||||
.flatMap(m=>[...m.cssRules]).filter(r=>/#pzBox/.test(r.selectorText||'')).map(r=>({sel:r.selectorText,mh:r.style.getPropertyValue('min-height'),pos:r.style.getPropertyValue('position')})))`));
|
||||
assert.ok(rules.some((r) => /#pzBox \.btns \.b/.test(r.sel) && parseFloat(r.mh) >= 40), 'touch targets');
|
||||
assert.ok(rules.some((r) => /^#pzBox ?> ?\.btns$/.test(r.sel) && r.pos === 'sticky'), 'pinned actions');
|
||||
assert.ok(ev("[...document.querySelectorAll('#pzBox button')].every(b=>b.classList.contains('b'))"), 'every sheet button is a .b the rule sizes');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('puzzles in every language', () => {
|
||||
for (const lang of ['de', 'es', 'fr', 'it', 'pt']) {
|
||||
const { ev, errors } = load({ lang });
|
||||
ev("ACT.puzzleMenu({});pzBegin(pzDef('baltic'))");
|
||||
build(ev, REF.baltic.three);
|
||||
ev("selectCity('hel');renderAll()");
|
||||
const seen = ev("['pzBox','modalCard','hud','panelBody'].map(id=>document.getElementById(id).textContent).join(' ')");
|
||||
assert.ok(!/puzzles\./.test(seen), `${lang}: no raw labels`);
|
||||
assert.match(seen, /⭐/);
|
||||
assert.deepEqual(errors, [], lang);
|
||||
}
|
||||
});
|
||||
|
||||
test('no clock in a puzzle: days never pass, nothing breaks, no bills', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("pzBegin(pzDef('hello'))");
|
||||
build(ev, REF.hello.three);
|
||||
ev('ACT.speed({v:8});ACT.phonePlay({});for(let i=0;i<50;i++)frame(performance.now()+i*3000)');
|
||||
assert.equal(ev('S.day'), 0);
|
||||
assert.equal(ev('UI.speed'), 0);
|
||||
assert.equal(ev('S.inc.length'), 0);
|
||||
assert.equal(ev('S.cash'), ev('START_CASH'), 'nothing is charged');
|
||||
assert.equal(ev("document.getElementById('left').hidden"), true, 'no goals/deals/NOC/networks drawer');
|
||||
assert.equal(ev("document.getElementById('pzBox').hidden"), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the main save is byte-identical before and after playing and solving a puzzle', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e7;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});save(true);window.__slot=UI.slot");
|
||||
let before = ev("slotRaw(UI.slot||window.__slot)");
|
||||
const name = ev('S.name'), day = ev('S.day');
|
||||
ev('ACT.puzzleMenu({})');
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /Hello, World/);
|
||||
ev("ACT.pzStart({id:'hello'})");
|
||||
assert.equal(ev('S.mode'), 'puzzle');
|
||||
before = ev("slotRaw(window.__slot)");// entering saves the network once more (a new stamp, the same game)
|
||||
assert.equal(JSON.parse(before).name, name);
|
||||
build(ev, REF.hello.three);
|
||||
ev("save(true);for(let i=0;i<5;i++)frame(performance.now()+6000*i);window.dispatchEvent(new Event('pagehide'));ACT.exportSave({})");
|
||||
assert.equal(ev("slotRaw(UI.slot||window.__slot)"), before, 'untouched while in the puzzle');
|
||||
assert.equal(ev("JSON.parse(localStorage.getItem('sot-puzzles')).s.hello.st"), 3, 'the stars are kept');
|
||||
ev('ACT.pzLeave({})');
|
||||
assert.equal(ev('S.mode'), 'normal');
|
||||
assert.equal(ev('S.name'), name);
|
||||
assert.equal(ev('S.day'), day);
|
||||
assert.ok(ev('!!S.pops.ams'));
|
||||
assert.equal(ev('UI.started'), true);
|
||||
assert.equal(ev("slotRaw(UI.slot||window.__slot)"), before, 'and after');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('leaving a puzzle with no game goes back to the title screen', () => {
|
||||
const { ev, errors } = load();
|
||||
assert.ok(ev("!!document.querySelector('#modalCard .door[data-door=puzzle]')"), 'the title screen has a Puzzles door');
|
||||
ev("document.querySelector('#modalCard .door[data-door=puzzle]').click()");
|
||||
ev("document.querySelector('#modalCard [data-act=pzStart]').click()");
|
||||
assert.equal(ev('S.mode'), 'puzzle');
|
||||
ev('ACT.pzLeave({})');
|
||||
assert.equal(ev('S'), null);
|
||||
assert.equal(ev("slotIdx(true).length"), 0, 'no network was saved');
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /Series/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('main-game toasts and leftover buttons do nothing in a puzzle', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e7;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});save(true)");
|
||||
ev("toast('main game news','bad',[{l:'Fix',act:'opsOpen',args:{}}]);save(true)");
|
||||
assert.ok(ev("document.querySelectorAll('#toasts .toast').length") > 0);
|
||||
ev("window.__slot=UI.slot;ACT.pzStart({id:'hello'})");
|
||||
const before = ev("slotRaw(__slot)");
|
||||
assert.equal(ev("[...document.querySelectorAll('#toasts .toast')].filter(t=>/main game news/.test(t.textContent)).length"), 0, 'main-game toasts are cleared');
|
||||
ev("ACT.pzPop({city:'lon'})");
|
||||
const st = () => ev("JSON.stringify({p:S.pops,l:S.links.length,c:S.cash,m:S.mode,te:!!S.te,ops:S.ops,sc:S.scrubs.length,dash:$('dash').hidden,bank:$('bankBox').hidden,left:$('left').hidden,modal:$('modal').hidden,cam:[cam.x,cam.y]})");
|
||||
const s0 = st();
|
||||
for (const a of ["opsOpen({})", "peerPol({p:'closed'})", "leftTab({t:'noc'})", "focusCity({city:'par'})", "fixInc({id:'x'})", "custGo({id:'x'})", "bank({})", "dash({})",
|
||||
"exportSave({})", "launchBB({city:'lon'})", "ad({city:'lon'})", "addRouter({city:'lon'})", "upRouter({city:'lon'})", "addSite({city:'lon'})", "buyTE({})",
|
||||
"buildScrub({city:'lon',tier:0})", "buildPop({city:'par'})", "buyTransit({city:'lon',net:'cog',tier:1})", "scenarios({})", "share({})", "importGo({})", "cont({})", "start({})", "newgame({})"]) {
|
||||
ev('ACT.' + a);
|
||||
assert.equal(st(), s0, `${a} does nothing in a puzzle`);
|
||||
}
|
||||
assert.equal(ev('S.mode'), 'puzzle');
|
||||
// A leftover toast button is a no-op too, through the real click path.
|
||||
ev("toast('stray','',[{l:'Go',act:'opsOpen',args:{}}]);document.querySelector('#toasts [data-act=opsOpen]').click()");
|
||||
assert.equal(st(), s0);
|
||||
ev("toast('puzzle news','good')");
|
||||
ev('ACT.pzLeave({})');
|
||||
assert.equal(ev("document.querySelectorAll('#toasts .toast').length"), 0, 'puzzle toasts do not follow you home');
|
||||
assert.equal(ev("slotRaw(__slot)"), before);
|
||||
// Back in the main game, the same actions work again.
|
||||
ev("ACT.addRouter({city:'ams'})");
|
||||
assert.equal(ev('S.pops.ams.routers'), 2);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a city to avoid reads as a rule, not a goal that can fail', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("pzBegin(pzDef('nofra'))");
|
||||
const tw = () => ev("[...document.querySelectorAll('#pzBox .pztw')].map(x=>x.className+'|'+x.textContent).join('\\n')");
|
||||
assert.match(tw(), /pztw rule\|🚫 Rule: not via Frankfurt/);
|
||||
assert.doesNotMatch(tw(), /[✓✗].*Frankfurt/);
|
||||
build(ev, REF.nofra.three);
|
||||
assert.match(tw(), /pztw rule\|🚫 Rule: not via Frankfurt/, 'still a rule once solved');
|
||||
assert.equal(evalP(ev).stars, 3);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a POP in a thin market costs its higher monthly rent too, and the panel says so', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("pzBegin(pzDef('kiwi'))");
|
||||
assert.ok(ev('colo("suv")') > 1, 'Suva is a thin market');
|
||||
assert.equal(ev("pzPopCost('suv')"), ev("popCost('suv')+12*popMo('suv')"));
|
||||
assert.ok(ev("pzPopCost('suv')") > ev("popCost('suv')+12*POP_MO"));
|
||||
ev("selectCity('suv')");
|
||||
assert.ok(ev("document.getElementById('panelBody').textContent").includes(ev("fmt$(popMo('suv'))") + '/mo'));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('each pack\'s idea is needed: three stars without it fail, and the one-star builds are not secretly three', () => {
|
||||
const { ev, errors } = load();
|
||||
const stars = (id, steps) => { ev(`pzBegin(pzDef('${id}'))`); build(ev, steps); return evalP(ev).stars; };
|
||||
const packs = JSON.parse(ev('JSON.stringify(Object.fromEntries(PZ.map(p=>[p.id,p.pack])))'));
|
||||
for (const id of Object.keys(REF)) {
|
||||
// A ring puzzle's cheapest delivering build is a ring, which is already N-1.
|
||||
if (id !== 'fire') assert.ok(stars(id, REF[id].one) < 3, `${id}: the one-star reference earns three stars`);
|
||||
if (packs[id] === 'rodeo') assert.ok(stars(id, REF[id].three.filter((s) => s[0] !== '@rt')) < 3, `${id}: three stars on the starter routers`);
|
||||
if (REF[id].three.some((s) => s[0] === '@route')) assert.ok(stars(id, REF[id].three.filter((s) => s[0] !== '@route')) < 3, `${id}: three stars without the routing choice`);
|
||||
// N-1 Club: the brute-force answer (every one-star link doubled) is over budget or not N-1.
|
||||
if (packs[id] === 'n1') assert.ok(stars(id, [...REF[id].one, ...links(REF[id].one)]) < 3, `${id}: doubling every link earns three stars`);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('every puzzle tells two tubes in one trench from two separate paths, zoomed out too', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.pzStart({id:'eurotrip'});closeModal()");
|
||||
build(ev, [['ams', 'fra', 'land', 1], ['ams', 'fra', 'land', 1, 1], ['ams', 'lon', 'nshuttle', 1], ['ams', 'lon', 'concerto', 1]]);
|
||||
ev("cam.z=0.6;drawFrame(performance.now())");
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(AR_PILLS.map(p=>p[2]).sort())")), ['2× one trench', '✓ 2 paths']);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -268,7 +268,7 @@ test('several exchanges per city: overlapping members, cheaper challengers, sepa
|
|||
const t = ev("document.getElementById('panelBody').textContent");
|
||||
assert.match(t, /3 exchanges compete/);
|
||||
assert.match(t, /NL-Nyx/);
|
||||
ev("save();load2=JSON.parse(localStorage.getItem('sot-save-v1'));sanitize(load2)");
|
||||
ev("save();load2=JSON.parse(slotRaw(UI.slot));sanitize(load2)");
|
||||
assert.equal(ev("load2.ixp['ams~2']"), 1, 'saves keep challenger ports');
|
||||
ev("ACT.cancelIx({city:'ams~2'});ACT.cancelIx({city:'ams~2'})");
|
||||
assert.equal(ev("S.ixp['ams~2']"), undefined);
|
||||
|
|
@ -563,8 +563,10 @@ test('the Amazon doubles overland fiber, and there is a national-operator scenar
|
|||
assert.equal(ev('S.scn.id'), 'ixbr');
|
||||
assert.equal(ev('brIxN()'), 0);
|
||||
ev("S.cash=1e9;for(const c of ['sao','rio','mao'])ACT.buildPop({city:c});S.ixp.sao=1;S.ixp.mao=1;compute()");
|
||||
assert.equal(ev('brIxN()'), 2);
|
||||
assert.equal(ev('brIxN()'), 1, 'a Manaus port on a POP the backbone does not reach does not count');
|
||||
assert.equal(ev("scnProg().items[1].v"), 1, 'Manaus step done');
|
||||
ev("S.links.push({id:'y1',a:'sao',b:'mao',km:2700,sub:false,kind:'wave',tier:0,mo:1});compute()");
|
||||
assert.equal(ev('brIxN()'), 2, 'joined up, it counts');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
|
@ -605,12 +607,13 @@ test('Africa: more countries, cables along both coasts, border costs and Cape to
|
|||
test('Australia: hard mode start in Sydney, dear transit and waves, cheap IX ports, NBN takes its cut', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("showTitle()");
|
||||
assert.ok(ev("!!document.querySelector('.start[data-city=\"syd\"]')"), 'Sydney is on the start screen');
|
||||
assert.ok(ev("!!document.querySelector('#homeSel optgroup:first-child option[value=syd]')"), 'Sydney is among the suggested homes');
|
||||
ev("ACT.pickStart({city:'syd'});ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0");
|
||||
assert.equal(ev('S.home'), 'syd');
|
||||
assert.equal(ev("regionMult('syd')"), 3, 'transit into Australia costs more than Asia');
|
||||
assert.ok(ev("regionMult('syd')>regionMult('sin')&®ionMult('syd')<regionMult('icn')"));
|
||||
assert.equal(ev("regionMult('akl')"), 1.8, 'Auckland keeps the Oceania price');
|
||||
assert.ok(ev("regionMult('akl')") < ev('AU_TRANSIT'), 'Auckland is not priced like Australia');
|
||||
assert.equal(ev("regionMult('akl')"), ev("Math.round(1.8*txComp('akl')*10)/10"), 'Auckland pays the Oceania price, adjusted for its market');
|
||||
assert.equal(ev("waveMarket('syd','lax',true).reg"), 2.6, 'any subsea wave touching Australia');
|
||||
assert.equal(ev("waveMarket('mel','syd',false).reg"), 1.8);
|
||||
assert.ok(ev("ixPortMo('syd',1)<PORT[1].ix"), 'IX ports are the cheap exception');
|
||||
|
|
@ -669,8 +672,10 @@ test('Fibre to the Basement: own fibre skips the wholesale cut but pays the levy
|
|||
assert.equal(ev("SCN.find(s=>s.id==='fttb').ok()"), false, 'still needs cables overseas');
|
||||
ev("S.links.push({id:'x1',a:'syd',b:'tok',km:8000,sub:true,cable:'sushi',kind:'wave',tier:1,mo:1},{id:'x2',a:'per',b:'sin',km:4000,sub:true,cable:'avo',kind:'wave',tier:1,mo:1},{id:'x3',a:'mel',b:'hba',km:600,sub:true,cable:'ferry',kind:'wave',tier:1,mo:1})");
|
||||
assert.equal(ev('auExits()'), 2, 'Bass Strait does not count as overseas');
|
||||
assert.equal(ev("SCN.find(s=>s.id==='fttb').ok()"), false, 'still needs the traffic');
|
||||
ev('R.served=FTTB_G');
|
||||
assert.equal(ev("SCN.find(s=>s.id==='fttb').ok()"), true);
|
||||
assert.equal(ev("SCN_PROG.fttb().length"), 6);
|
||||
assert.equal(ev("SCN_PROG.fttb().length"), 7);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
|
@ -898,10 +903,11 @@ test('submarine terminal and engineering upgrades commission independently and c
|
|||
test('new subsea builds include chosen transmission packages in the quote and saved order', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
try {
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=4;S.won=true;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'lon'});ACT.buildPop({city:'nyc'});UI.lmode='df';UI.dfSrc='cable';openLinkModal('lon','nyc')");
|
||||
const baseline = JSON.parse(ev("JSON.stringify(seaQuote('lon','nyc'))"));
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=4;S.won=true;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'sin'});ACT.buildPop({city:'lax'});UI.lmode='df';UI.dfSrc='cable';openLinkModal('sin','lax')");
|
||||
// Across the Pacific, where the two packages together lift it from 400G to 800G (#198).
|
||||
const baseline = JSON.parse(ev("JSON.stringify(seaQuote('sin','lax'))"));
|
||||
ev("document.querySelector('#modalCard [data-act=seaPackage][data-args*=terminal]').click();document.querySelector('#modalCard [data-act=seaPackage][data-args*=engineering]').click()");
|
||||
const quote = JSON.parse(ev("JSON.stringify(seaQuote('lon','nyc','standard',{terminal:true,engineering:true}))"));
|
||||
const quote = JSON.parse(ev("JSON.stringify(seaQuote('sin','lax','standard',{terminal:true,engineering:true}))"));
|
||||
assert.equal(quote.days, baseline.days + 210);
|
||||
assert.equal(quote.cost, baseline.cost + 5000000 + 12000000 + baseline.km * 1000);
|
||||
assert.equal(quote.ms, baseline.ms);
|
||||
|
|
@ -972,9 +978,12 @@ test('own subsea cables after #78: refunds of what was paid, upgrades a route ne
|
|||
const syd = JSON.parse(ev("JSON.stringify(S.links.at(-1))"));
|
||||
assert.equal(syd.b, 'syd'); assert.equal(syd.subterminal, syd.ready);
|
||||
ev('S.day=S.links.at(-1).ready'); assert.equal(ev("optG('tp16',S.links.at(-1))"), 400, 'lit across 18,387 km');
|
||||
// upgrades bought later count toward the price; sanitize keeps a sane price and drops junk
|
||||
// engineering adds nothing once the terminals light it (#198); upgrades bought later count toward the price
|
||||
ev("S.links.at(-1).subengineering=undefined;ACT.subUpgrade({id:S.links.at(-1).id,k:'engineering'})");
|
||||
assert.equal(ev('S.links.at(-1).paid'), syd.paid);
|
||||
ev("S.links.at(-1).subterminal=undefined;ACT.subUpgrade({id:S.links.at(-1).id,k:'engineering'})");
|
||||
assert.ok(ev('S.links.at(-1).paid') > syd.paid);
|
||||
// sanitize keeps a sane price and drops junk
|
||||
ev("S.links.at(-1).paid='lots';S.links[0].paid=-5;S=sanitize(S)");
|
||||
assert.equal(ev('S.links.at(-1).paid'), undefined); assert.equal(ev('S.links[0].paid'), undefined);
|
||||
// advice about upgrades only on cables you own
|
||||
|
|
@ -1034,16 +1043,16 @@ test('an old save with Australian POPs is told once that Australia changed', ()
|
|||
const a = load();
|
||||
start(a.ev);
|
||||
a.ev("ACT.buildPop({city:'syd'});for(let d=0;d<3;d++)dayTick();delete S.auV;save()");
|
||||
const sv = a.ev("localStorage.getItem('sot-save-v1')");
|
||||
const sv = a.ev("slotRaw(UI.slot)");
|
||||
const { ev, errors } = load({ storage: { 'sot-save-v1': sv } });
|
||||
assert.match(ev("S.log.map(e=>e.t).join(' | ')"), /Australia got more Australian/);
|
||||
assert.equal(ev("S.auV"), 1);
|
||||
assert.equal(ev("S.auNews"), undefined, 'only once');
|
||||
const again = load({ storage: { 'sot-save-v1': ev("save();localStorage.getItem('sot-save-v1')") } });
|
||||
const again = load({ storage: { 'sot-save-v1': ev("save();slotRaw(UI.slot)") } });
|
||||
assert.equal(again.ev("S.log.filter(e=>/Australia got more Australian/.test(e.t)).length"), 1, 'not told twice');
|
||||
// a new game never sees it, and neither does a save without Australia
|
||||
const b = load(); start(b.ev); b.ev("for(let d=0;d<3;d++)dayTick();delete S.auV;save()");
|
||||
const c = load({ storage: { 'sot-save-v1': b.ev("localStorage.getItem('sot-save-v1')") } });
|
||||
const c = load({ storage: { 'sot-save-v1': b.ev("slotRaw(UI.slot)") } });
|
||||
assert.doesNotMatch(c.ev("S.log.map(e=>e.t).join(' | ')"), /Australia got more/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -1070,3 +1079,30 @@ test('city density: no small city crowds a bigger one, Brazil is slimmer than Eu
|
|||
ev('cam.x=CITY.cpv.x;cam.y=CITY.cpv.y;cam.z=6;draw(0)');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('prices follow real connectivity: thin markets cost more, hubs stay put', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(Object.keys(CITY_PDB).filter(c=>!CITY[c]))')), [], 'every entry is a city on the map');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(CITIES.filter(c=>!CITY_PDB[c.id]).map(c=>c.id))')), [], 'every city has data, so none keeps the plain price by accident');
|
||||
assert.ok(ev('Object.values(CITY_PDB).every(q=>Array.isArray(q)&&q.length===3&&q.every(x=>Number.isInteger(x)&&x>=0)&&q[1]>=0)'), '[facilities, presences, ASNs], whole numbers');
|
||||
// The cities that used to have none: thin markets cost more than Frankfurt, and the Arctic has no neutral data center.
|
||||
for (const c of ['dus', 'rix', 'mct', 'mle', 'fuk', 'sju', 'kin', 'anc', 'tik']) assert.ok(ev(`txComp('${c}')`) > 1, `${c} is no hub`);
|
||||
for (const c of ['brw', 'tik', 'pvs', 'hav']) assert.equal(ev(`colo('${c}')`), 1.5, `${c}: no carrier-neutral data center`);
|
||||
assert.ok(ev("txComp('dus')") < ev("txComp('rix')") && ev("txComp('rix')") < ev("txComp('mle')"), 'Düsseldorf, Riga, Malé: ever thinner');
|
||||
// A city without data keeps the plain regional price.
|
||||
assert.equal(ev("(()=>{const q=CITY_PDB.fra;delete CITY_PDB.fra;const r=[txComp('fra'),colo('fra'),popMo('fra')];CITY_PDB.fra=q;return r.join()})()"), `1,1,${ev('POP_MO')}`);
|
||||
assert.equal(ev("regionMult('syd')"), ev('AU_TRANSIT'), 'Australia keeps its hand-set transit price');
|
||||
for (const c of ['fra', 'ams', 'lon', 'nyc']) assert.equal(ev(`txComp('${c}')`), 1, `${c} is a hub`);
|
||||
assert.equal(ev("regionMult('sao')"), 1.6, 'São Paulo keeps the South American price');
|
||||
assert.ok(ev("regionMult('rbr')") > ev("regionMult('sao')") * 1.5, 'Rio Branco has few sellers');
|
||||
assert.ok(ev("txComp('rbr')") <= 1.8);
|
||||
assert.equal(ev("colo('rbr')"), 1.5, 'no neutral data center');
|
||||
assert.equal(ev("popCost('rbr')"), ev('POP_COST') * 1.5);
|
||||
assert.equal(ev("popMo('fra')"), ev('POP_MO'));
|
||||
ev("ACT.buildPop({city:'rbr'});compute()");
|
||||
assert.ok(ev('R.cost.pops') >= ev("popMo('rbr')"), 'running cost uses the city rent');
|
||||
ev("selectCity('rbr')");
|
||||
assert.ok(ev("CITY_PDB.sao[2]>=2000&&CITY_PDB.nyc[2]>=2000&&CITY_PDB.kgl[2]<2000"), 'Brazil and the US are dense in ASNs, Rwanda is not');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
|
|||
34
tests/release-story.test.js
Normal file
34
tests/release-story.test.js
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
// A big release can open with a story: shown in full in "What's new", and on GitHub above every change.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const path = require('node:path');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const RN = path.join(__dirname, '..', 'scripts', 'release-notes.js');
|
||||
const run = (...a) => JSON.parse(execFileSync(process.execPath, [RN, ...a], { encoding: 'utf8' }));
|
||||
|
||||
test('the release notes script reads a story and the bullets apart', () => {
|
||||
const story = run('2.0.0', '--story'), notes = run('2.0.0');
|
||||
assert.ok(story.length >= 5, 'the 2.0 story has its paragraphs');
|
||||
assert.match(story[0], /one game, four doors/);
|
||||
for (const w of ['Normal', 'Sandbox', 'Puzzles', 'Architect runs', 'Scenarios', 'chaos monkey']) assert.ok(story.some((p) => p.includes(w)), `the story introduces ${w}`);
|
||||
assert.ok(story.every((p) => !p.startsWith('- ') && !p.startsWith('#')), 'no bullets or headings in the story');
|
||||
assert.ok(notes.length >= 50, 'every change is still a bullet');
|
||||
assert.ok(notes.every((n) => !n.startsWith('**')), 'no story paragraph among the bullets');
|
||||
assert.deepEqual(run('1.37.0', '--story'), [], 'most releases have none');
|
||||
});
|
||||
|
||||
test('"What\'s new" tells the story in full, with every change one tap away', () => {
|
||||
const { ev, errors } = load();
|
||||
const story = run('2.0.0', '--story');
|
||||
ev(`RELEASE_STORY.splice(0,0,...${JSON.stringify(story)});RELEASE_NOTES.splice(0,0,...${JSON.stringify(run('2.0.0'))})`);
|
||||
ev('openModal(notesHtml(RELEASE_NOTES,APP_VERSION))');
|
||||
const html = ev("document.getElementById('modalCard').innerHTML"), text = ev("document.getElementById('modalCard').textContent");
|
||||
assert.equal(ev("document.querySelectorAll('#modalCard .story p').length"), story.length, 'every paragraph, no "and N more"');
|
||||
assert.match(html, /<b>Normal<\/b>/, 'bold leads');
|
||||
assert.doesNotMatch(text, /\*\*/);
|
||||
assert.equal(ev("document.querySelectorAll('#modalCard ul.notes').length"), 0, 'no clipped bullet list under it');
|
||||
assert.match(html, /releases\/tag\/v/, 'and the full notes on GitHub');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -20,10 +20,11 @@ test('bugs and ideas point to GitHub from the menu and How to play, and the chat
|
|||
}
|
||||
});
|
||||
|
||||
test('the GitHub card fits a phone', () => {
|
||||
test('the GitHub link fits a phone: a small link next to the chat link in the menu', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});window.innerWidth=360;ACT.menu()");
|
||||
assert.ok(ev('isPhone()'));
|
||||
assert.ok(ev(`!!document.querySelector('#modal a.plug[href="${ISSUES}"] .go')`), 'same card layout as the chat card');
|
||||
assert.ok(ev(`!!document.querySelector('#modal .menu-plugs a.mplug[href="${ISSUES}"]')`), 'bug link in the menu');
|
||||
assert.ok(ev(`!!document.querySelector('#modal .menu-plugs a.mplug[href="'+SIGNAL+'"]')`), 'chat link beside it');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
|
|||
31
tests/router-art.test.js
Normal file
31
tests/router-art.test.js
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
// Every router model has its own picture, shown where you pick and compare models.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
test('every router model has a picture, and each one is valid SVG', () => {
|
||||
const { ev, dom } = load();
|
||||
assert.equal(ev('RG_ART.length'), ev('RG.length'), 'one picture per model, in RG order');
|
||||
const n = ev('RG.length');
|
||||
for (let g = 0; g < n; g++) {
|
||||
const s = ev(`rgArt(${g})`);
|
||||
const doc = new dom.window.DOMParser().parseFromString(s.replace('<svg ', '<svg xmlns="http://www.w3.org/2000/svg" '), 'image/svg+xml');
|
||||
assert.equal(doc.getElementsByTagName('parsererror').length, 0, `model ${g} parses`);
|
||||
assert.ok(doc.querySelectorAll('path,rect,circle,ellipse').length > 8, `model ${g} draws something`);
|
||||
}
|
||||
assert.equal(new Set(Array.from({ length: n }, (_, g) => ev(`rgArt(${g})`))).size, n, 'no two models look the same');
|
||||
assert.equal(ev('rgArt(99)'), '');
|
||||
});
|
||||
|
||||
test('only the POP overview shows a picture: its model, left of the city name', () => {
|
||||
const { ev, errors, dom } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;selectCity(S.home);UI.tab='links';UI.models=true;renderAll()");
|
||||
const pics = dom.window.document.querySelectorAll('#panel .rgpic');
|
||||
assert.equal(pics.length, 1, 'the model in use only, not the list of other models');
|
||||
assert.ok(dom.window.document.querySelector('#panel .ph > .rgpic.big svg.rgart'), 'in the header, beside the name');
|
||||
ev("UI.tab='cust';renderAll()");
|
||||
assert.equal(dom.window.document.querySelectorAll('#panel .rgpic').length, 1, 'on every tab');
|
||||
ev("selectCity(Object.keys(CITY).find(c=>!S.pops[c]&&!CITY[c].off));renderAll()");
|
||||
assert.equal(dom.window.document.querySelectorAll('#panel .rgpic').length, 0, 'no POP, no router');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -40,12 +40,13 @@ test('indexed routing matches the simple allocation loop across network changes'
|
|||
"S.transit.filter(t=>t.net==='tly').forEach(t=>{t.carry=true})",
|
||||
"S.transit.filter(t=>t.net==='lvl').forEach((t,i)=>{t.pref=i%2?'low':'normal'})",
|
||||
"S.pni.forEach((p,i)=>p.pref=i%3===0?'high':i%3===1?'low':'normal')",
|
||||
"S.te={on:true,script:''}",
|
||||
"S.te={on:true,script:''};S.core={lv:2,run:2,legacy:true}",
|
||||
"S.te.script='prefer pni for goggle\\nspill at 80%\\navoid transit for netchill'",
|
||||
"S.te.script='avoid transit level tree\\nprefer transit tell-ya\\nspill at 80%'",
|
||||
"S.te.script='prefer transit Cogentle\\nprepend transit Cogentle 2\\nprotect customers'",
|
||||
"S.ev.rpki={nets:['ggl','nfx'],until:S.day+3};S.ev.depeer=S.day+3",
|
||||
"S.ev.ddos={city:'fra',until:S.day+3,gbps:300,vec:'syn',entry:{k:'edge'}}",
|
||||
"S.ev.ddosMore=[{id:'x2',city:'nyc',until:S.day+3,gbps:200,vec:'http',entry:{k:'t',id:'transit4'}}]",
|
||||
"S.links[0].eqDown=S.day+2;S.links[1].cut=S.day+2;S.links[2].loss={until:S.day+2,f:0.5}",
|
||||
"S.links[4].chFail={until:S.day+2,o:'tp16'};S.links[6].ch.push('zr4');S.links[8].regen=2",
|
||||
"S.day+=4;S.pni.splice(0,20);S.caches.splice(0,10);S.transit[0].pref='high'",
|
||||
|
|
@ -61,3 +62,28 @@ test('indexed routing matches the simple allocation loop across network changes'
|
|||
} finally { dom.window.close(); }
|
||||
});
|
||||
|
||||
|
||||
// Islands: POPs no backbone joins. Exit lists are split per island (a flow only scans exits it can reach),
|
||||
// and must route exactly like the full scan, also when a cut splits an island or joins two.
|
||||
test('indexed routing matches the simple allocation loop on a network of islands', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
try {
|
||||
network(ev);
|
||||
ev("S.links=S.links.filter(l=>!['df4','df9','w3','w4','w8','w9'].includes(l.id));compute()");
|
||||
assert.ok(ev("Object.keys(S.pops).some(c=>!pathExists('fra',c))"), 'the network is in pieces');
|
||||
const changes = [
|
||||
'',
|
||||
"S.pni.forEach((p,i)=>p.pref=i%3===0?'high':i%3===1?'low':'normal')",
|
||||
"S.te={on:true,script:'prefer pni for goggle\\nspill at 80%'};S.core={lv:2,run:2,legacy:true}",
|
||||
"S.ev.ddos={city:'fra',until:S.day+3,gbps:300,vec:'syn',entry:{k:'edge'}}",
|
||||
"S.links[0].cut=S.day+2",
|
||||
"S.te=null;S.links[0].cut=0;S.links.push({id:'join',a:'par',b:'pek',kind:'wave',tier:2,km:8000,cut:0,mo:100})",
|
||||
];
|
||||
for (const change of changes) {
|
||||
ev(change);
|
||||
ev('window.priorR=JSON.stringify(R);referenceCompute();window.expectedR=JSON.stringify(R);R=JSON.parse(priorR);compute()');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(R)')), JSON.parse(ev('expectedR')), change || 'baseline');
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
} finally { dom.window.close(); }
|
||||
});
|
||||
|
|
|
|||
45
tests/rules-locked.test.js
Normal file
45
tests/rules-locked.test.js
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
// The rules follow from the mode when a save loads: an edited or imported save cannot change them (2.0).
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
test('a loaded save gets the rules of its mode, whatever its rules say', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("beginGame('T','fra',{mode:'normal'});if(UI.pendGame)ACT.pitchSkip()");
|
||||
const base = JSON.parse(ev('JSON.stringify(packSave(S))'));
|
||||
const loadAs = (mut) => { const s = JSON.parse(JSON.stringify(base)); mut(s); ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(s))}))`); return JSON.parse(ev('JSON.stringify(S.rules)')); };
|
||||
const preset = (p, o) => JSON.parse(ev(`JSON.stringify(makeRules('${p}'${o ? ',' + JSON.stringify(o) : ''}))`));
|
||||
// Normal games keep one of the three Normal presets, with nothing changed.
|
||||
for (const p of ['freeze', 'oncall', 'bgp']) assert.deepEqual(loadAs(s => { s.rules = { preset: p }; }), preset(p));
|
||||
assert.deepEqual(loadAs(s => { s.rules = { preset: 'oncall', money: 'infinite', gates: 'open', chaos: 'none', lead: 'quick' }; }), preset('oncall'), 'no free money or open gates in On-call');
|
||||
assert.deepEqual(loadAs(s => { s.rules = { preset: 'freeze', clock: false }; }), preset('freeze'), 'the clock always runs');
|
||||
assert.deepEqual(loadAs(s => { s.rules = { preset: 'puzzle' }; }), preset('oncall'), 'no puzzle rules (clock off for ever) in a Normal game');
|
||||
assert.deepEqual(loadAs(s => { s.rules = { preset: 'sandbox' }; }), preset('oncall'), 'no sandbox powers without the sandbox tag');
|
||||
assert.deepEqual(loadAs(s => { delete s.rules; }), preset('oncall'), 'a save from before 2.0 is On-call');
|
||||
// Sandboxes keep only their chaos.
|
||||
assert.deepEqual(loadAs(s => { s.mode = 'sandbox'; s.rules = { preset: 'sandbox', chaos: 'spicy', clock: false, money: 'normal' }; }), preset('sandbox', { chaos: 'spicy' }));
|
||||
assert.deepEqual(loadAs(s => { s.mode = 'sandbox'; s.rules = { preset: 'bgp' }; }), preset('sandbox'));
|
||||
// Scenarios and the weekly run on On-call.
|
||||
const scn = { id: 'pac', rules: {}, days: 1095, name: 'x', mods: [] };
|
||||
for (const r of [{ preset: 'bgp' }, { preset: 'oncall', chaos: 'none' }, { preset: 'sandbox' }, { preset: 'freeze' }])
|
||||
assert.deepEqual(loadAs(s => { s.mode = 'scenario'; s.scn = scn; s.rules = r; }), preset('oncall'), JSON.stringify(r));
|
||||
assert.deepEqual(loadAs(s => { s.mode = 'scenario'; s.scn = { ...scn, id: 'weekly', key: '2026-W44' }; s.rules = { preset: 'freeze' }; }), preset('oncall'), 'the weekly too');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a save that claims to be a puzzle loads as a Normal On-call game with the clock running', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("beginGame('T','fra',{mode:'normal'});if(UI.pendGame)ACT.pitchSkip()");
|
||||
const s = JSON.parse(ev('JSON.stringify(packSave(S))'));
|
||||
s.mode = 'puzzle'; s.rules = { preset: 'puzzle' };
|
||||
ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(s))}));UI.started=true;compute()`);
|
||||
assert.equal(ev('S.mode'), 'normal');
|
||||
assert.equal(ev('pzOn()'), false);
|
||||
assert.equal(ev("rule('clock')"), true);
|
||||
ev('for(let i=0;i<3;i++)dayTick()');
|
||||
assert.equal(ev('S.day'), 3, 'days pass');
|
||||
ev(`UI.importing=JSON.parse(${JSON.stringify(JSON.stringify(s))});ACT.importGo()`);
|
||||
assert.equal(ev('S.mode'), 'normal');
|
||||
assert.equal(ev('rulePreset()'), 'oncall');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
188
tests/rules.test.js
Normal file
188
tests/rules.test.js
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const start = (ev, o) => ev(`beginGame('Rule Testers','fra',${JSON.stringify(o)});if(UI.pendGame)ACT.pitchSkip()`);
|
||||
// Days of a quiet-ish network until n failures have fired, on a fixed seed.
|
||||
const fails = (ev, days) => { ev("S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});__reseed(4242)"); ev(`for(let i=0;i<${days};i++)dayTick()`); return ev('S.inc.length+S.stats.survived+(S.stats.incidents||0)'); };
|
||||
|
||||
test('an old save without rules loads as On-call, a sandbox save as Sandbox', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()");
|
||||
const old = JSON.parse(ev('JSON.stringify(S)')); delete old.rules;
|
||||
ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(old))}))`);
|
||||
assert.equal(ev('rulePreset()'), 'oncall');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.rules)')), JSON.parse(ev("JSON.stringify(makeRules('oncall'))")));
|
||||
assert.equal(ev("rule('chaos')"), 'normal');
|
||||
assert.equal(ev('chaosMul()'), 1);
|
||||
old.mode = 'sandbox';
|
||||
ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(old))}))`);
|
||||
assert.equal(ev('rulePreset()'), 'sandbox');
|
||||
assert.equal(ev("rule('money')"), 'infinite');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('rules survive save and load, and junk is repaired', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev, { mode: 'normal', preset: 'bgp' });
|
||||
assert.equal(ev('rulePreset()'), 'bgp');
|
||||
ev("const t=JSON.stringify(packSave(S));S=migrate(JSON.parse(t))");
|
||||
assert.equal(ev('rulePreset()'), 'bgp');
|
||||
assert.equal(ev("rule('chaos')"), 'spicy');
|
||||
ev("S.rules={preset:'freeze',chaos:'apocalypse',lead:42,market:'yes',mods:['ok',7,'<b>']};sanitize(S)");
|
||||
assert.equal(ev('rulePreset()'), 'freeze');
|
||||
assert.equal(ev("rule('chaos')"), 'calm', 'a bad value falls back to the preset');
|
||||
assert.equal(ev("rule('lead')"), 'quick');
|
||||
assert.equal(ev("rule('market')"), false);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.rules.mods)')), ['ok']);
|
||||
ev("S.rules={preset:'nope'};sanitize(S)");
|
||||
assert.equal(ev('rulePreset()'), 'oncall');
|
||||
ev("S.rules='hello';sanitize(S)");
|
||||
assert.equal(ev('rulePreset()'), 'oncall');
|
||||
// a scenario always runs on On-call, whatever was asked for
|
||||
ev("beginGame('X','nyc',{scn:SCN.find(s=>s.id==='spat'),preset:'freeze'})");
|
||||
assert.equal(ev('rulePreset()'), 'oncall');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the title screen: four doors, three Normal presets, a chaos picker for Sandbox, at 360 px', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
const doc = dom.window.document;
|
||||
ev('window.innerWidth=360;showTitle()');
|
||||
assert.equal(doc.querySelectorAll('#modal .door').length, 4);
|
||||
assert.equal(doc.querySelectorAll('#modal .preset').length, 3);
|
||||
assert.equal(doc.querySelectorAll('#modal .chs').length, 4);
|
||||
assert.equal(doc.getElementById('doorSandbox').hidden, true);
|
||||
assert.ok(doc.querySelector('.preset[data-preset=oncall].on'), 'On-call is the default');
|
||||
doc.querySelector('.preset[data-preset=freeze]').click();
|
||||
assert.ok(doc.querySelector('.preset[data-preset=freeze].on'));
|
||||
doc.querySelector('.door[data-door=sandbox]').click();
|
||||
assert.equal(doc.getElementById('doorSandbox').hidden, false);
|
||||
assert.equal(doc.getElementById('doorNormal').hidden, true);
|
||||
doc.querySelector('.chs[data-chaos=spicy]').click();
|
||||
doc.querySelector('.door[data-door=normal]').click();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()");
|
||||
assert.equal(ev('rulePreset()'), 'freeze');
|
||||
assert.match(ev("document.getElementById('hAsn').textContent"), /Change Freeze/);
|
||||
assert.match(ev("document.getElementById('hAsn').title"), /locked/);
|
||||
ev('showTitle()');
|
||||
doc.querySelector('.door[data-door=sandbox]').click();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()");
|
||||
assert.equal(ev('S.mode'), 'sandbox');
|
||||
assert.equal(ev("rule('chaos')"), 'spicy', 'the sandbox remembers the chaos it was given');
|
||||
ev('showTitle()');
|
||||
doc.querySelector('.door[data-door=scn]').click();
|
||||
assert.match(doc.getElementById('modalCard').textContent, /Weekly challenge/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('On-call shows no extra tag; the share card names other presets', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev, { mode: 'normal' });
|
||||
assert.equal(ev('ruleTag()'), '');
|
||||
assert.match(ev("document.getElementById('hAsn').textContent"), /^AS\d+$/);
|
||||
start(ev, { mode: 'normal', preset: 'bgp' });
|
||||
assert.match(ev('ruleTag()'), /BGP at 3/);
|
||||
ev('ACT.share()');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('Sandbox lays its own subsea cable without being Tier 1, and passes the level gates', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev, { mode: 'sandbox' });
|
||||
assert.equal(ev('gatesOpen()'), true);
|
||||
assert.equal(ev('S.won'), false);
|
||||
assert.equal(ev('lvl()'), ev('LEVELS.length'));
|
||||
ev("ACT.buildPop({city:'lon'});ACT.buildPop({city:'nyc'});compute()");
|
||||
assert.equal(ev("ownCabWhy('lon','nyc')"), '');
|
||||
ev("UI.lmode='df';UI.via=null;openLinkModal('lon','nyc');ACT.ownCab()");
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /frankly rude amount of money/);
|
||||
ev('ACT.orderCable()');
|
||||
assert.ok(ev("S.links.some(l=>l.own&&l.sub)"), 'the cable is being laid');
|
||||
// and the normal game still says Tier 1 only
|
||||
start(ev, { mode: 'normal' });
|
||||
assert.match(ev("ownCabWhy('lon','nyc')"), /Tier 1/);
|
||||
assert.equal(ev('lvl()'), 1);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('Sandbox chaos: none by default, but it can be asked for', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev, { mode: 'sandbox' });
|
||||
assert.equal(ev("rule('chaos')"), 'none');
|
||||
ev('S.cash=5;for(let i=0;i<150;i++)dayTick()');
|
||||
assert.equal(ev('S.stats.incidents'), 0);
|
||||
assert.ok(ev('S.cash') >= 1e8);
|
||||
start(ev, { mode: 'sandbox', rules: { chaos: 'spicy' } });
|
||||
assert.equal(ev("rule('chaos')"), 'spicy');
|
||||
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});for(let i=0;i<200;i++)dayTick()");
|
||||
assert.ok(ev('S.stats.incidents') > 0, 'spicy sandboxes break');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('Change Freeze breaks less than On-call, BGP at 3 a.m. more, on the same seed', () => {
|
||||
const n = {};
|
||||
for (const p of ['freeze', 'oncall', 'bgp']) {
|
||||
const { ev, errors } = load();
|
||||
start(ev, { mode: 'normal', preset: p });
|
||||
n[p] = fails(ev, 720);
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
assert.ok(n.freeze < n.oncall, `freeze ${n.freeze} < on-call ${n.oncall}`);
|
||||
assert.ok(n.bgp > n.oncall, `bgp ${n.bgp} > on-call ${n.oncall}`);
|
||||
});
|
||||
|
||||
test('chaos stretches spicy outages and leaves On-call ones alone', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev, { mode: 'normal', preset: 'bgp' });
|
||||
ev("S.day=10;S.pops.fra.down=12;addInc({type:'crash',ref:'fra',until:12,msg:'x',cost:0})");
|
||||
assert.equal(ev('S.inc[0].until'), 13);
|
||||
assert.equal(ev('S.pops.fra.down'), 13, 'what it holds down lasts as long');
|
||||
start(ev, { mode: 'normal' });
|
||||
ev("S.day=10;S.pops.fra.down=12;addInc({type:'crash',ref:'fra',until:12,msg:'x',cost:0})");
|
||||
assert.equal(ev('S.inc[0].until'), 12);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('quick lead times: PNIs, dark fiber and own builds arrive in days (#151)', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev, { mode: 'normal', preset: 'freeze' });
|
||||
ev("S.cash=1e9;S.lvl=4;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:1})");
|
||||
const p = JSON.parse(ev("JSON.stringify(S.pni.find(x=>x.net==='nfx'))"));
|
||||
assert.ok(p && p.ready - ev('S.day') <= 37, `PNI in days (${p && p.ready - ev('S.day')})`);
|
||||
assert.ok(ev('dfBuildDays(500)') <= 40);
|
||||
assert.equal(ev('leadDays(30)'), 3);
|
||||
// On-call: as quoted
|
||||
start(ev, { mode: 'normal' });
|
||||
assert.equal(ev('leadDays(30)'), 30);
|
||||
assert.equal(ev('dfBuildDays(500)'), 245);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('Change Freeze: no hardware market, no sold-out routes', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev, { mode: 'normal', preset: 'freeze' });
|
||||
ev("S.cash=1e9;ACT.buyIx({city:'fra',tier:1,signed:true})");
|
||||
ev('S.day=2000');
|
||||
assert.equal(ev("hwMul('rt')"), 1, 'no inflation');
|
||||
assert.equal(ev("hwCard()"), '');
|
||||
assert.equal(ev("[0,1,2,3,4,5,6].some(t=>CITIES.slice(0,60).some(c=>soldOut('fra',c.id,t)))"), false);
|
||||
start(ev, { mode: 'normal' });
|
||||
ev('S.day=2000');
|
||||
assert.ok(ev("hwMul('rt')") > 1, 'On-call keeps the market');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('no clock: dayTick advances no days, sends no bills, and the speed buttons hide', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev, { mode: 'normal' });
|
||||
ev("S.rules=makeRules('puzzle');S.mode='puzzle';const c=S.cash;window.__c=c;for(let i=0;i<50;i++)dayTick();renderHUD()");
|
||||
assert.equal(ev('S.day'), 0);
|
||||
assert.equal(ev('S.cash'), ev('__c'));
|
||||
assert.equal(ev("document.getElementById('sp1').hidden"), true);
|
||||
ev("ACT.speed({v:4})");
|
||||
assert.notEqual(ev('UI.speed'), 4);
|
||||
ev("window.innerWidth=360;renderTabbar()");
|
||||
assert.equal(ev("!!document.querySelector('#tabbar [data-act=phonePlay]')"), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
73
tests/sales-trial.test.js
Normal file
73
tests/sales-trial.test.js
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// The sales trial (#185, the intern's sales order) runs the pass with the offer first and skips the pass without
|
||||
// it when it cannot change the answer. It must sign exactly the offers the original two-pass trial signs.
|
||||
const ORIGINAL = `(function(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null;
|
||||
const T=BIZ_T[o.type],b=offerCustomer(o);if(T.event&&(!(o.start>S.day)||!(o.dur>0)))return null;
|
||||
if(o.type==='capfib'&&S.biz.some(x=>x.type==='capfib'&&capPend(x)&&!x.link&&((x.city===o.city&&x.city2===o.city2)||(x.city===o.city2&&x.city2===o.city))))return null;
|
||||
if(T.fiber){const l=o.type==='capfib'?capFibLink(b):S.links.find(x=>x.id===o.link);if(!l)return null;b.link=l.id;
|
||||
if(!fiberOk(b)||(o.type==='wwave'&&(!(o.slots>0)||freeCh(l)<o.slots))||(o.type==='dfpair'&&!pairFree(l))||
|
||||
(o.type==='pairs'&&(!l.own||S.biz.some(x=>x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type)))))return null;}
|
||||
const state=S,result=R,hot=UI.hotMap,future=S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day);
|
||||
try{S={...S,biz:S.biz};
|
||||
if(future){S.biz=S.biz.map(x=>BIZ_T[x.type].event&&x.start>S.day?{...x,start:S.day}:x);compute();}
|
||||
const healthy=S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute();
|
||||
return !bizWhy(b).length&&healthy.every(x=>!bizWhy(x).length)?b:null;
|
||||
}finally{S=state;R=result;UI.hotMap=hot;b.start=o.start;if(T.cap)delete b.live;}})`;
|
||||
|
||||
test('the faster sales trial signs exactly the offers the two-pass trial signs', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
try {
|
||||
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();window.slowOffer=${ORIGINAL};`);
|
||||
assert.ok(ev('S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day)'), 'the fixture has events booked ahead, so the shortcut runs');
|
||||
const seen = { yes: 0, no: 0, skipped: 0, third: 0 };
|
||||
ev('window.__n=0;const _c=compute;window.compute=function(){__n++;return _c.apply(this,arguments)}');
|
||||
for (let day = 0; day < 6; day++) {
|
||||
ev(`__reseed(${1000 + day});S.offers=[];for(let i=0;i<10;i++)spawnOffer();`);
|
||||
// Small offers that fit, and on alternate days a squeeze, so offers fail on capacity and on others' service too.
|
||||
ev(`for(const o of S.offers)o.bw=Math.max(1,Math.round(o.bw*${day % 2 ? 1 : 0.05}))`);
|
||||
if (day % 2) ev('for(const c in S.pops)S.pops[c].bb&&(S.pops[c].bb.d*=1.3)');
|
||||
// And circuits over the busiest links, which take bandwidth from customers who had it.
|
||||
ev(`for(const l of S.links.filter(l=>!linkDown(l)&&S.pops[l.a]&&S.pops[l.b]&&R.load[l.id]>1).sort((x,y)=>R.load[y.id]/capOf(y)-R.load[x.id]/capOf(x)).slice(${day},${day}+2))
|
||||
S.offers.push({id:'sq'+l.id,city:l.a,city2:l.b,name:'Squeeze',type:'l2vpn',bw:${day % 2 ? 300 : 2},rate:100,reqs:[],exp:S.day+30})`);
|
||||
for (const id of JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))'))) {
|
||||
const o = `S.offers.find(x=>x.id===${JSON.stringify(id)})`;
|
||||
const before = ev('JSON.stringify(R.load)+R.served');
|
||||
ev('__n=0');const fast = ev(`JSON.stringify(autoOffer(${o}))`);const n = ev('__n');
|
||||
assert.equal(ev('JSON.stringify(R.load)+R.served'), before, 'a trial leaves the live result alone');
|
||||
const slow = ev(`JSON.stringify(slowOffer(${o}))`);
|
||||
assert.equal(fast, slow, `offer ${id} (${ev(`${o}.type`)}) on day ${day}`);
|
||||
if (fast !== 'null') seen.yes++; else seen.no++;
|
||||
if (n === 1) seen.skipped++;
|
||||
if (n === 2) seen.third++;
|
||||
}
|
||||
ev('S.nextFail=S.day+99;S.nextEvent=S.day+99;dayTick()');
|
||||
}
|
||||
assert.ok(seen.yes >= 3 && seen.no >= 3, `both answers come up (${JSON.stringify(seen)})`);
|
||||
assert.ok(seen.skipped >= 5, `the second pass is often skipped (${JSON.stringify(seen)})`);
|
||||
assert.ok(seen.third >= 3, `and run when the offer hurts someone (${JSON.stringify(seen)})`);
|
||||
assert.deepEqual(errors, []);
|
||||
} finally { dom.window.close(); }
|
||||
});
|
||||
|
||||
test('with a scenic circuit the sales trial keeps both passes in their original order', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
try {
|
||||
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.biz.find(b=>BIZ_T[b.type].l2).route='scenic';compute();window.slowOffer=${ORIGINAL};`);
|
||||
ev('window.__n=0;const _c=compute;window.compute=function(){__n++;return _c.apply(this,arguments)}');
|
||||
ev('__reseed(77);S.offers=[];for(let i=0;i<6;i++)spawnOffer();');
|
||||
for (const id of JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))'))) {
|
||||
const o = `S.offers.find(x=>x.id===${JSON.stringify(id)})`;
|
||||
ev('__n=0');const fast = ev(`JSON.stringify(autoOffer(${o}))`);const n = ev('__n');
|
||||
assert.equal(fast, ev(`JSON.stringify(slowOffer(${o}))`), id);
|
||||
assert.ok(n === 0 || n === 2, 'both passes, as before');
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
} finally { dom.window.close(); }
|
||||
});
|
||||
|
|
@ -4,7 +4,7 @@ const { load } = require('./harness');
|
|||
|
||||
// Make the browser's storage refuse the save: 'QuotaExceededError' (too big) or 'SecurityError' (not allowed).
|
||||
const refuse = name => `window.__err=${JSON.stringify(name)};{const P=Object.getPrototypeOf(localStorage),set=P.setItem;
|
||||
P.setItem=function(k,v){if(k==='sot-save-v1'&&__err){const e=new Error('no');e.name=__err;throw e;}return set.call(this,k,v);};}`;
|
||||
P.setItem=function(k,v){if(k.startsWith('sot-save-v1')&&__err){const e=new Error('no');e.name=__err;throw e;}return set.call(this,k,v);};}`;
|
||||
|
||||
test('#176 a save that does not fit tells the player once, with Export, and the menu says so', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
|
|
@ -55,8 +55,8 @@ test('#176 saves leave customer defaults out, and loading puts them back exactly
|
|||
assert.deepEqual(norm(after), norm(want));
|
||||
assert.equal(ev("S.biz.find(b=>b.id==='l2').route"), 'fast', 'a chosen route is kept');
|
||||
assert.equal(ev("S.biz.find(b=>b.id==='w7').what"), ev("wwWhat(S.links.find(l=>l.id==='df1'),4)"), 'alien waves get their description back');
|
||||
assert.match(ev("localStorage.getItem('sot-save-v1')"), /"Carrier 1"/);
|
||||
assert.doesNotMatch(ev("localStorage.getItem('sot-save-v1')"), /alien wave on your/, 'descriptions are not stored');
|
||||
assert.match(ev("slotRaw(UI.slot)"), /"Carrier 1"/);
|
||||
assert.doesNotMatch(ev("slotRaw(UI.slot)"), /alien wave on your/, 'descriptions are not stored');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
|
@ -77,7 +77,7 @@ const huge = "for(let i=0;i<12000;i++){const slots=1+i%4;S.biz.push({id:'h'+i,ci
|
|||
test('#176 small saves stay plain JSON, written at once', () => {
|
||||
const { ev, errors } = load({ gzip: true });
|
||||
ev("ACT.start({});save(true)");
|
||||
assert.equal(ev("localStorage.getItem('sot-save-v1')[0]"), '{');
|
||||
assert.equal(ev("slotRaw(UI.slot)[0]"), '{');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
|
@ -86,8 +86,8 @@ test('#176 a huge save is gzipped into storage and the next visit loads it', asy
|
|||
a.ev(bigBiz + ';' + huge);
|
||||
assert.ok(a.ev('JSON.stringify(packSave(S)).length') >= a.ev('GZ_MIN'), 'big enough to compress');
|
||||
a.ev('save(true)');
|
||||
await settle(a.ev, "(localStorage.getItem('sot-save-v1')||'').startsWith(GZ)");
|
||||
const raw = a.ev("localStorage.getItem('sot-save-v1')"), full = a.ev('JSON.stringify(packSave(S)).length');
|
||||
await settle(a.ev, "(slotRaw(UI.slot)||'').startsWith(GZ)");
|
||||
const raw = a.ev("slotRaw(UI.slot)"), full = a.ev('JSON.stringify(packSave(S)).length');
|
||||
assert.ok(raw.length < full / 4, `much smaller in storage (${raw.length} vs ${full})`);
|
||||
const before = a.ev("JSON.stringify([S.name,S.day,S.biz.length,S.biz.find(b=>b.id==='h77').what])");
|
||||
// The next visit: the page unpacks it before booting and continues the same network.
|
||||
|
|
@ -102,22 +102,22 @@ test('#176 a newer save is never overwritten by an older one still compressing',
|
|||
const { ev, errors } = load({ gzip: true });
|
||||
ev(bigBiz + ';' + huge);
|
||||
ev("save(true);S.name='Newer';save(true);S.name='Newest';save(true)");
|
||||
await settle(ev, "!UI.gzBusy&&(localStorage.getItem('sot-save-v1')||'').startsWith(GZ)");
|
||||
ev("gunzip(localStorage.getItem('sot-save-v1')).then(t=>window.__t=JSON.parse(t).name)");
|
||||
await settle(ev, "!UI.gzBusy&&(slotRaw(UI.slot)||'').startsWith(GZ)");
|
||||
ev("gunzip(slotRaw(UI.slot)).then(t=>window.__t=JSON.parse(t).name)");
|
||||
await settle(ev, "!!window.__t");
|
||||
assert.equal(ev('__t'), 'Newest');
|
||||
// A new game started while a big save compresses: the old network does not come back.
|
||||
ev("save(true);ACT.newgame();ACT.start({});window.__new=S.name");
|
||||
await settle(ev, '!UI.gzBusy');
|
||||
assert.equal(ev("JSON.parse(localStorage.getItem('sot-save-v1')).name"), ev('__new'), 'the new game stays saved');
|
||||
assert.equal(ev("JSON.parse(slotRaw(UI.slot)).name"), ev('__new'), 'the new game stays saved');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#176 a damaged compressed save is kept aside and the player is told', async () => {
|
||||
test('#176 a damaged compressed save is kept, marked damaged, and the player is told', async () => {
|
||||
const { ev, dom, errors } = load({ gzip: true, storage: { 'sot-save-v1': 'gz:bm90IGd6aXA=' } });
|
||||
await settle(ev, "localStorage.getItem('sot-save-broken')!==null");
|
||||
assert.match(dom.window.document.body.textContent, /could not be/);
|
||||
assert.equal(ev("localStorage.getItem('sot-save-broken')"), 'gz:bm90IGd6aXA=');
|
||||
assert.equal(ev("localStorage.getItem('sot-save-v1')"), null);
|
||||
await settle(ev, "slotIdx().length===1&&/could not be/.test(document.getElementById('toasts').textContent)");
|
||||
assert.equal(ev("slotIdx()[0].broken"), true, 'listed as damaged, so it can still be exported or deleted');
|
||||
assert.equal(ev("slotRaw('main')"), 'gz:bm90IGd6aXA=', 'the damaged save is kept as it was');
|
||||
assert.equal(ev('!!UI.started'), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
|
|||
435
tests/save-slots.test.js
Normal file
435
tests/save-slots.test.js
Normal file
|
|
@ -0,0 +1,435 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load, browser, flush } = require('./harness');
|
||||
|
||||
// Two windows of one browser share localStorage, its storage events, a BroadcastChannel and Web Locks; a reload is a
|
||||
// new window with the same tab (sessionStorage).
|
||||
const settle = async (ev, cond, what) => { for (let i = 0; i < 400 && !ev(cond); i++) await new Promise((r) => setTimeout(r, 5)); assert.ok(ev(cond), what || cond); };
|
||||
const play = (ev, name, city = 'fra', days = 5) => ev(`UI.pitched=true;UI.nm=${JSON.stringify(name)};if($('nmIn'))$('nmIn').value=UI.nm;ACT.pickStart({city:'${city}'});ACT.start({});ACT.launchBB({city:'${city}'});for(let i=0;i<${days};i++)dayTick();save(true)`);
|
||||
const idx = (ev) => JSON.parse(ev("JSON.stringify(slotIdx())"));
|
||||
const card = (ev) => ev("document.getElementById('modalCard').textContent");
|
||||
|
||||
// A save as the previous version wrote it: one key, no index.
|
||||
function legacySave() {
|
||||
const a = load();
|
||||
a.ev("$('nmIn').value='Old Faithful';ACT.start({});ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});for(let i=0;i<30;i++)dayTick();UI.speed=2");
|
||||
return { txt: a.ev('JSON.stringify(packSave((S.uiSpeed=UI.speed,S.cam={x:cam.x,y:cam.y,z:cam.z},S)))'), snap: a.ev('JSON.stringify([S.name,S.day,S.cash,S.asn,Object.keys(S.pops),S.transit.length])') };
|
||||
}
|
||||
|
||||
test('the single save of older versions becomes the first network, losslessly, and loads exactly as before', async () => {
|
||||
const { txt, snap } = legacySave();
|
||||
const b = browser();
|
||||
const a = load({ browser: b, storage: { 'sot-save-v1': txt } });
|
||||
await settle(a.ev, 'UI.started===true');
|
||||
assert.equal(a.ev('JSON.stringify([S.name,S.day,S.cash,S.asn,Object.keys(S.pops),S.transit.length])'), snap, 'the same network');
|
||||
assert.equal(a.ev('UI.speed'), 2);
|
||||
assert.equal(b.ls.get('sot-save-v1:main'), txt, 'copied byte for byte');
|
||||
assert.equal(b.ls.get('sot-save-v1'), txt, 'the old key stays as a fallback until the network saves again');
|
||||
const e = idx(a.ev);
|
||||
assert.equal(e.length, 1);
|
||||
assert.equal(e[0].id, 'main');
|
||||
assert.equal(e[0].name, 'Old Faithful');
|
||||
assert.equal(e[0].day, 30);
|
||||
// The copy was read back before the index was written.
|
||||
const i = b.log.findIndex((x) => x[0] === 'set' && x[1] === 'sot-save-v1:main'), r = b.log.findIndex((x, n) => n > i && x[0] === 'get' && x[1] === 'sot-save-v1:main'), w = b.log.findIndex((x) => x[0] === 'set' && x[1] === 'sot-slots');
|
||||
assert.ok(i >= 0 && r > i && w > r, 'write new, read it back, then the index');
|
||||
a.ev('dayTick();save(true)');
|
||||
assert.equal(b.ls.has('sot-save-v1'), false, 'after a later save, the old key is retired');
|
||||
assert.equal(JSON.parse(b.ls.get('sot-save-v1:main')).day, 31);
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('a browser with no room for the copy keeps playing from the old key', async () => {
|
||||
const { txt } = legacySave();
|
||||
const b = browser();
|
||||
b.quota = 10;// every slot write is refused
|
||||
const a = load({ browser: b, storage: { 'sot-save-v1': txt } });
|
||||
await settle(a.ev, 'UI.started===true');
|
||||
assert.equal(a.ev('S.name'), 'Old Faithful');
|
||||
assert.equal(b.ls.has('sot-save-v1:main'), false);
|
||||
assert.equal(b.ls.get('sot-save-v1'), txt, 'never touched');
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('a compressed (gz) single save migrates and loads the same network', async () => {
|
||||
const g = load({ gzip: true });
|
||||
const raw = await g.dom.window.eval(`(async()=>{$('nmIn').value='Squeezed';ACT.start({});for(let i=0;i<8;i++)dayTick();return gzip(JSON.stringify(packSave(S)));})()`);
|
||||
const day = g.ev('S.day');
|
||||
assert.ok(raw.startsWith('gz:'));
|
||||
const b = browser();
|
||||
const a = load({ browser: b, gzip: true, storage: { 'sot-save-v1': raw } });
|
||||
await settle(a.ev, 'UI.started===true');
|
||||
assert.equal(a.ev('S.name'), 'Squeezed');
|
||||
assert.equal(a.ev('S.day'), day);
|
||||
assert.equal(b.ls.get('sot-save-v1:main'), raw);
|
||||
assert.equal(idx(a.ev)[0].name, 'Squeezed', 'the index knows its name without unpacking it again');
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('two networks coexist and load independently; the title lists them, newest first', async () => {
|
||||
const b = browser();
|
||||
const a = load({ browser: b });
|
||||
play(a.ev, 'First Net', 'fra', 4);
|
||||
const first = a.ev('UI.slot');
|
||||
a.ev('ACT.toTitle()');
|
||||
assert.equal(a.ev('S'), null);
|
||||
play(a.ev, 'Second Net', 'nyc', 9);
|
||||
const second = a.ev('UI.slot');
|
||||
assert.notEqual(first, second);
|
||||
a.ev('ACT.toTitle()');
|
||||
const list = a.ev("[...document.querySelectorAll('#slotList .slot b')].map(b=>b.textContent).join('|')");
|
||||
assert.equal(list, 'Second Net|First Net', 'most recent first');
|
||||
assert.match(card(a.ev), /Your networks/);
|
||||
a.ev(`ACT.cont({id:'${first}'})`);
|
||||
await settle(a.ev, 'UI.started===true');
|
||||
assert.equal(a.ev('S.name'), 'First Net');
|
||||
assert.equal(a.ev('S.day'), 4);
|
||||
assert.equal(a.ev('S.home'), 'fra');
|
||||
a.ev('ACT.toTitle()');
|
||||
a.ev(`ACT.cont({id:'${second}'})`);
|
||||
await settle(a.ev, 'UI.started===true');
|
||||
assert.equal(a.ev('S.name'), 'Second Net');
|
||||
assert.equal(a.ev('S.day'), 9);
|
||||
assert.equal(JSON.parse(b.ls.get('sot-save-v1:' + first)).name, 'First Net', 'each in its own key');
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('the title lists networks from the index alone, without reading any save', () => {
|
||||
const b = browser();
|
||||
const a = load({ browser: b });
|
||||
play(a.ev, 'One');
|
||||
a.ev('ACT.toTitle()');
|
||||
play(a.ev, 'Two');
|
||||
a.ev('ACT.toTitle()');
|
||||
b.log.length = 0;
|
||||
a.ev('showTitle()');
|
||||
assert.deepEqual(b.log.filter((x) => x[1].startsWith('sot-save-v1')), [], 'no save was read');
|
||||
assert.equal(a.ev("document.querySelectorAll('#slotList .slot').length"), 2);
|
||||
});
|
||||
|
||||
test('each tab continues its own network on reload, and two tabs play two networks at once', async () => {
|
||||
const b = browser();
|
||||
const tab1 = new Map(), tab2 = new Map();
|
||||
const w1 = load({ browser: b, tab: tab1 });
|
||||
play(w1.ev, 'Tab One', 'fra', 3);
|
||||
const w2 = load({ browser: b, tab: tab2 });
|
||||
await flush();
|
||||
assert.equal(w2.ev('!!UI.started'), false, 'the only network is open in tab one, so tab two shows the title');
|
||||
play(w2.ev, 'Tab Two', 'sin', 6);
|
||||
// Both keep saving, each into its own slot.
|
||||
w1.ev('dayTick();save(true)');w2.ev('dayTick();save(true)');
|
||||
// Reload tab one: it comes back to its own network, not the newer one.
|
||||
b.close(w1.dom.window);
|
||||
const r1 = load({ browser: b, tab: tab1 });
|
||||
await settle(r1.ev, 'UI.started===true');
|
||||
assert.equal(r1.ev('S.name'), 'Tab One');
|
||||
assert.equal(r1.ev('S.day'), 4);
|
||||
b.close(w2.dom.window);
|
||||
const r2 = load({ browser: b, tab: tab2 });
|
||||
await settle(r2.ev, 'UI.started===true');
|
||||
assert.equal(r2.ev('S.name'), 'Tab Two');
|
||||
// A brand-new tab: the title with both, and Continue offers neither, since both are open.
|
||||
const w3 = load({ browser: b });
|
||||
await flush();
|
||||
assert.equal(w3.ev('!!UI.started'), false);
|
||||
assert.equal(w3.ev("document.querySelectorAll('#slotList .slot.busy').length"), 2);
|
||||
assert.equal(w3.ev("!!document.querySelector('#modalCard [data-act=cont].pink')"), false, 'no Continue for a network open elsewhere');
|
||||
// Tab two goes back to the title: its network is free again and becomes the one to continue.
|
||||
r2.ev('ACT.toTitle()');
|
||||
await flush();
|
||||
w3.ev('showTitle()');
|
||||
assert.match(w3.ev("document.querySelector('#modalCard [data-act=cont].pink').textContent"), /Tab Two/);
|
||||
for (const w of [r1, r2, w3]) assert.deepEqual(w.errors, []);
|
||||
});
|
||||
|
||||
test('opening a network open in another window offers to switch or take over, and take-over hands it across', async () => {
|
||||
const b = browser();
|
||||
const w1 = load({ browser: b });
|
||||
play(w1.ev, 'Shared Net', 'fra', 3);
|
||||
const id = w1.ev('UI.slot');
|
||||
const w2 = load({ browser: b });
|
||||
await flush();
|
||||
w2.ev(`ACT.cont({id:'${id}'})`);
|
||||
await flush();
|
||||
assert.match(card(w2.ev), /open in another window/);
|
||||
assert.equal(w2.ev('!!UI.started'), false, 'not forked');
|
||||
assert.ok(w2.ev("!!document.querySelector('#modalCard [data-act=slotSwitch]')&&!!document.querySelector('#modalCard [data-act=slotTake]')"));
|
||||
// Switch: the other window says hello, this one stays on the title.
|
||||
w2.ev(`ACT.slotSwitch({id:'${id}'})`);
|
||||
await flush();
|
||||
assert.match(w1.ev("document.getElementById('toasts').textContent"), /Here it is/);
|
||||
// Take over: window one saves what it has, steps aside calmly and stops saving.
|
||||
w1.ev('dayTick()');
|
||||
w2.ev(`ACT.slotTake({id:'${id}'})`);
|
||||
await settle(w2.ev, 'UI.started===true', 'taken over');
|
||||
assert.equal(w2.ev('S.day'), 4, 'with the last day played in the other window');
|
||||
await settle(w1.ev, '/opened in another window/.test(document.getElementById(\'modalCard\').textContent)');
|
||||
assert.equal(w1.ev('UI.slot'), null);
|
||||
assert.equal(w1.ev('S'), null);
|
||||
w2.ev('dayTick();save(true)');
|
||||
const before = b.ls.get('sot-save-v1:' + id);
|
||||
w1.ev("save(true);dispatchEvent(new Event('pagehide'))");
|
||||
assert.equal(b.ls.get('sot-save-v1:' + id), before, 'the window that stepped aside never writes again');
|
||||
assert.equal(JSON.parse(before).day, 5);
|
||||
assert.deepEqual(w1.errors, []);
|
||||
assert.deepEqual(w2.errors, []);
|
||||
});
|
||||
|
||||
test('without Web Locks or BroadcastChannel the heartbeat still keeps one writer per network', async () => {
|
||||
const b = browser({ locks: false, channel: false });
|
||||
const w1 = load({ browser: b });
|
||||
play(w1.ev, 'Old Browser Net');
|
||||
const id = w1.ev('UI.slot');
|
||||
w1.ev('slotBeat()');
|
||||
const w2 = load({ browser: b });
|
||||
await flush();
|
||||
assert.equal(w2.ev('slotBusy(' + JSON.stringify(id) + ')'), true);
|
||||
w2.ev(`ACT.cont({id:'${id}'})`);
|
||||
await flush();
|
||||
assert.match(card(w2.ev), /open in another window/);
|
||||
w2.ev(`ACT.slotTake({id:'${id}'})`);
|
||||
await settle(w2.ev, 'UI.started===true');
|
||||
w2.ev('slotBeat()');
|
||||
await settle(w1.ev, 'UI.slot===null', 'the first window notices the new heartbeat');
|
||||
assert.deepEqual(w1.errors, []);
|
||||
assert.deepEqual(w2.errors, []);
|
||||
});
|
||||
|
||||
test('a stale write is refused: a newer save of the same network from another window is never overwritten', async () => {
|
||||
const b = browser();
|
||||
const w1 = load({ browser: b });
|
||||
play(w1.ev, 'Contested');
|
||||
const id = w1.ev('UI.slot');
|
||||
// Another window (a forked tab, a crashed lock) saves a newer version behind this one's back.
|
||||
const ix = JSON.parse(b.ls.get('sot-slots'));
|
||||
const newer = JSON.parse(b.ls.get('sot-save-v1:' + id));newer.day = 99;newer.sv = { seq: 1000, at: Date.now() };
|
||||
b.ls.set('sot-save-v1:' + id, JSON.stringify(newer));
|
||||
ix.slots[0].seq = 1000;ix.slots[0].day = 99;b.ls.set('sot-slots', JSON.stringify(ix));
|
||||
w1.ev('dayTick();save(true)');
|
||||
assert.equal(JSON.parse(b.ls.get('sot-save-v1:' + id)).day, 99, 'the newer save stays');
|
||||
assert.match(card(w1.ev), /saved in another window/);
|
||||
assert.equal(w1.ev('UI.slot'), null, 'and this window stops saving');
|
||||
assert.ok(w1.ev("!!document.querySelector('#modalCard [data-act=cont]')"), 'with a way to load the newest version');
|
||||
// The storage event alone also stops it, before it even tries.
|
||||
const w2 = load({ browser: b });
|
||||
await flush();
|
||||
play(w2.ev, 'Watcher');
|
||||
const id2 = w2.ev('UI.slot'), ix2 = JSON.parse(b.ls.get('sot-slots')), e = ix2.slots.find((x) => x.id === id2);
|
||||
e.seq += 50;
|
||||
w1.dom.window.localStorage.setItem('sot-slots', JSON.stringify(ix2));// written by another window: w2 gets the event
|
||||
await settle(w2.ev, 'UI.slot===null');
|
||||
assert.deepEqual(w1.errors, []);
|
||||
assert.deepEqual(w2.errors, []);
|
||||
});
|
||||
|
||||
test('saves are written slot first, then the index, and every write moves the sequence on', () => {
|
||||
const b = browser();
|
||||
const a = load({ browser: b });
|
||||
play(a.ev, 'Ordered');
|
||||
const id = a.ev('UI.slot');
|
||||
b.log.length = 0;
|
||||
a.ev('dayTick();save(true)');
|
||||
const sets = b.log.filter((x) => x[0] === 'set').map((x) => x[1]);
|
||||
assert.ok(sets.indexOf('sot-save-v1:' + id) < sets.indexOf('sot-slots'), sets.join());
|
||||
const s = JSON.parse(b.ls.get('sot-save-v1:' + id)), e = idx(a.ev).find((x) => x.id === id);
|
||||
assert.equal(s.sv.seq, e.seq, 'the save and its index entry agree');
|
||||
a.ev('save(true)');
|
||||
assert.equal(JSON.parse(b.ls.get('sot-save-v1:' + id)).sv.seq, e.seq + 1);
|
||||
assert.equal(a.ev('"sv" in S'), false, 'the stamp lives in storage, not in the game');
|
||||
});
|
||||
|
||||
test('deleting a network removes its save and its line, after a confirmation', async () => {
|
||||
const b = browser();
|
||||
const a = load({ browser: b });
|
||||
play(a.ev, 'Keeper');
|
||||
a.ev('ACT.toTitle()');
|
||||
play(a.ev, 'Goner');
|
||||
const gone = a.ev('UI.slot');
|
||||
a.ev('ACT.toTitle()');
|
||||
a.ev(`document.querySelector('#slotList .slot[data-slot="${gone}"] .slot-more').click()`);
|
||||
assert.match(card(a.ev), /Goner/);
|
||||
a.ev("document.querySelector('#modalCard [data-act=slotDel]').click()");
|
||||
assert.match(card(a.ev), /cannot be undone/);
|
||||
assert.ok(b.ls.has('sot-save-v1:' + gone), 'nothing deleted before the confirmation');
|
||||
a.ev("document.querySelector('#modalCard [data-act=slotDelGo]').click()");
|
||||
assert.equal(b.ls.has('sot-save-v1:' + gone), false);
|
||||
assert.deepEqual(idx(a.ev).map((e) => e.name), ['Keeper']);
|
||||
assert.match(card(a.ev), /Continue Keeper/);
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('a network deleted in another window is never written back by the window playing it', async () => {
|
||||
const b = browser();
|
||||
const w1 = load({ browser: b });
|
||||
play(w1.ev, 'Doomed');
|
||||
const id = w1.ev('UI.slot');
|
||||
const w2 = load({ browser: b });
|
||||
await flush();
|
||||
w2.ev(`ACT.slotDelGo({id:'${id}'})`);
|
||||
await settle(w1.ev, 'UI.slot===null');
|
||||
w1.ev("save(true);dispatchEvent(new Event('pagehide'))");
|
||||
assert.equal(b.ls.has('sot-save-v1:' + id), false);
|
||||
assert.equal(idx(w2.ev).length, 0);
|
||||
assert.match(w1.ev("document.getElementById('toasts').textContent"), /deleted in another window/);
|
||||
});
|
||||
|
||||
test('export the network on screen, or any network from the list; import adds a new network and keeps the old', async () => {
|
||||
const b = browser();
|
||||
const a = load({ browser: b });
|
||||
const files = [];
|
||||
a.dom.window.URL.createObjectURL = (blob) => { files.push(blob); return 'blob:x'; };
|
||||
const text = (blob) => new Promise((r) => { const f = new a.dom.window.FileReader(); f.onload = () => r(f.result); f.readAsText(blob); });
|
||||
a.dom.window.URL.revokeObjectURL = () => {};
|
||||
play(a.ev, 'Exported Net', 'fra', 7);
|
||||
const first = a.ev('UI.slot');
|
||||
a.ev('ACT.exportSave({})');
|
||||
const txt = await text(files[0]);
|
||||
// Import it back: a second network, the first untouched.
|
||||
a.ev(`UI.importing=parseSave(${JSON.stringify(txt)}).s;ACT.importGo()`);
|
||||
assert.notEqual(a.ev('UI.slot'), first, 'a new slot');
|
||||
assert.equal(a.ev('S.name'), 'Exported Net');
|
||||
assert.equal(a.ev('S.day'), 7);
|
||||
assert.equal(idx(a.ev).length, 2);
|
||||
assert.equal(JSON.parse(b.ls.get('sot-save-v1:' + first)).day, 7, 'the first network is still there');
|
||||
// Export from the list: straight from storage, the same network.
|
||||
a.ev('ACT.toTitle()');
|
||||
a.ev(`ACT.slotExport({id:'${first}'})`);
|
||||
await settle(a.ev, 'true');await flush(5);
|
||||
const j = JSON.parse(await text(files[1]));
|
||||
assert.equal(j.app, 'series-of-tubes');
|
||||
assert.equal(j.S.name, 'Exported Net');
|
||||
assert.equal(a.ev(`parseSave(${JSON.stringify(JSON.stringify(j))}).err||null`), null, 'and it imports');
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('renaming the network renames it in the list', () => {
|
||||
const b = browser();
|
||||
const a = load({ browser: b });
|
||||
play(a.ev, 'Before');
|
||||
a.ev("ACT.menu();document.querySelector('#modalCard [data-act=rename]').click()");
|
||||
a.ev("document.getElementById('rnIn').value=' After Rename ';ACT.renameGo()");
|
||||
assert.equal(a.ev('S.name'), 'After Rename');
|
||||
assert.equal(idx(a.ev)[0].name, 'After Rename');
|
||||
});
|
||||
|
||||
test('puzzles never write a network, and a tab closed mid-puzzle keeps the network it set aside', async () => {
|
||||
const b = browser();
|
||||
const a = load({ browser: b });
|
||||
// A puzzle from the title: nothing saved at all.
|
||||
a.ev("ACT.pzStart({id:'hello'})");
|
||||
a.ev("save(true);dispatchEvent(new Event('pagehide'))");
|
||||
assert.equal(idx(a.ev).length, 0);
|
||||
a.ev('ACT.pzLeave({})');
|
||||
play(a.ev, 'Set Aside', 'fra', 3);
|
||||
const id = a.ev('UI.slot');
|
||||
a.ev("ACT.pzStart({id:'hello'})");
|
||||
const kept = b.ls.get('sot-save-v1:' + id);
|
||||
a.ev("S.pops.lon={day:0};save(true);for(let i=0;i<5;i++)frame(performance.now()+6000*i);dispatchEvent(new Event('pagehide'))");
|
||||
assert.equal(b.ls.get('sot-save-v1:' + id), kept, 'the puzzle never writes the slot');
|
||||
assert.equal(JSON.parse(kept).name, 'Set Aside');
|
||||
assert.ok(b.ls.has('sot-puzzles') || true);
|
||||
// The tab closes mid-puzzle; the next one continues the network.
|
||||
b.close(a.dom.window);
|
||||
const r = load({ browser: b });
|
||||
await settle(r.ev, 'UI.started===true');
|
||||
assert.equal(r.ev('S.name'), 'Set Aside');
|
||||
assert.equal(r.ev('S.mode'), 'normal');
|
||||
assert.deepEqual(a.errors, []);
|
||||
assert.deepEqual(r.errors, []);
|
||||
});
|
||||
|
||||
test('a big save still compressing when a puzzle starts lands in its network, and so does the next one', async () => {
|
||||
const b = browser();
|
||||
const a = load({ browser: b, gzip: true });
|
||||
play(a.ev, 'Big One', 'fra', 1);
|
||||
a.ev("S.cash=1e9;ACT.buildPop({city:'ams'});S.links.push({id:'df1',a:'fra',b:'ams',kind:'df',own:true,km:450,sys:'roadm',ch:[],ready:0,mo:500,day:0,cut:0});for(let i=0;i<12000;i++)S.biz.push({id:'h'+i,city:'fra',city2:'ams',name:'Huge Carrier '+i,type:'wwave',bw:1,rate:4000+i,mood:100,since:i,link:'df1',slots:1,what:''});compute()");
|
||||
const id = a.ev('UI.slot');
|
||||
a.ev("S.name='Big One v1';save(true);S.name='Big One v2';save(true)");// one compressing, one queued
|
||||
a.ev("ACT.pzStart({id:'hello'})");
|
||||
await settle(a.ev, '!UI.gzBusy&&!SLOT.gzQ.size');
|
||||
const t = await a.dom.window.eval(`gunzip(slotRaw(${JSON.stringify(id)}))`);
|
||||
assert.equal(JSON.parse(t).name, 'Big One v2', 'the queued save landed too');
|
||||
a.ev('ACT.pzLeave({})');
|
||||
assert.equal(a.ev('S.name'), 'Big One v2');
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('leaving a puzzle when the network cannot be loaded marks it damaged, and Continue does not crash', async () => {
|
||||
const b = browser();
|
||||
const a = load({ browser: b });
|
||||
play(a.ev, 'Fragile');
|
||||
const id = a.ev('UI.slot');
|
||||
a.ev("ACT.pzStart({id:'hello'})");
|
||||
// The network set aside is gone from memory and its save is unreadable (another version, a broken disk…).
|
||||
a.ev(`UI.pzKeep=null;localStorage.setItem(SLOT_K+${JSON.stringify(id)},'{"v":1,"day":"x","pops":7}')`);
|
||||
a.ev(`window.__m=migrate;migrate=s=>{if(s&&s.pops===7)throw new Error('bad');return __m(s);}`);
|
||||
a.ev('ACT.pzLeave({})');
|
||||
a.ev('migrate=__m');
|
||||
assert.match(a.ev("document.getElementById('toasts').textContent"), /could not be loaded/);
|
||||
assert.equal(idx(a.ev)[0].broken, true);
|
||||
assert.ok(b.ls.has('sot-save-v1:' + id), 'kept, so it can be exported');
|
||||
a.ev(`ACT.cont({id:${JSON.stringify(id)}})`);
|
||||
await flush();
|
||||
assert.equal(a.ev('!!UI.started'), false);
|
||||
a.ev('ACT.cont({})');
|
||||
assert.match(card(a.ev), /Series/);
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('a corrupted index is rebuilt from the saves themselves', async () => {
|
||||
const b = browser();
|
||||
const a = load({ browser: b });
|
||||
play(a.ev, 'Alpha', 'fra', 2);
|
||||
a.ev('ACT.toTitle()');
|
||||
play(a.ev, 'Beta', 'nyc', 3);
|
||||
a.ev('ACT.toTitle()');
|
||||
b.ls.set('sot-slots', '{not json');
|
||||
b.ls.set('sot-save-v1:junk1', 'garbage');
|
||||
const c = load({ browser: b });
|
||||
await flush();
|
||||
const names = idx(c.ev).map((e) => e.name || (e.broken ? '(damaged)' : '?')).sort();
|
||||
assert.deepEqual(names, ['(damaged)', 'Alpha', 'Beta']);
|
||||
assert.match(c.ev("document.getElementById('slotList').textContent"), /Damaged/);
|
||||
// An index line whose save is gone is dropped.
|
||||
const ix = JSON.parse(b.ls.get('sot-slots'));ix.slots.push({ id: 'ghost', name: 'Ghost', day: 1, at: Date.now() });b.ls.set('sot-slots', JSON.stringify(ix));
|
||||
c.ev('showTitle()');
|
||||
assert.equal(c.ev("idx=slotIdx().map(e=>e.name).includes('Ghost')"), false);
|
||||
assert.deepEqual(c.errors, []);
|
||||
});
|
||||
|
||||
test('out of room: the warning offers to free up space, listing the other networks by size', () => {
|
||||
const b = browser();
|
||||
const a = load({ browser: b });
|
||||
play(a.ev, 'Small Other');
|
||||
a.ev('ACT.toTitle()');
|
||||
play(a.ev, 'Growing');
|
||||
b.quota = 100;
|
||||
a.ev('UI.saveFail=null;dayTick();save(true)');
|
||||
assert.match(a.ev("document.getElementById('toasts').textContent"), /not being saved/);
|
||||
a.ev("document.querySelector('#toasts [data-act=slotSpace]').click()");
|
||||
assert.match(card(a.ev), /Small Other/);
|
||||
assert.ok(a.ev("!!document.querySelector('#modalCard [data-act=slotExport]')&&!!document.querySelector('#modalCard [data-act=slotDel]')"));
|
||||
a.ev('ACT.menu()');
|
||||
assert.ok(a.ev("!!document.querySelector('#modalCard [data-act=slotSpace]')"), 'the menu offers it too');
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('the networks list fits a 360 px phone and has a tap target and a ⋯ menu per network, in every language', () => {
|
||||
for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) {
|
||||
const b = browser();
|
||||
const a = load({ browser: b, lang: lang === 'en' ? undefined : lang });
|
||||
a.ev('window.innerWidth=360');
|
||||
play(a.ev, 'Phone Net One');
|
||||
a.ev('ACT.toTitle()');
|
||||
a.ev("UI.mode='sandbox'");
|
||||
play(a.ev, 'Sandy');
|
||||
a.ev('ACT.toTitle()');
|
||||
const rows = a.ev("document.querySelectorAll('#slotList .slot').length");
|
||||
assert.equal(rows, 2, lang);
|
||||
assert.ok(a.ev("[...document.querySelectorAll('#slotList .slot')].every(r=>r.querySelector('.slot-go')&&r.querySelector('.slot-more[aria-label]'))"), lang);
|
||||
assert.match(a.ev("document.getElementById('slotList').textContent"), /🏖️/, `${lang}: preset icon`);
|
||||
assert.equal(a.ev("document.querySelector('#slotList').previousElementSibling.textContent"), a.ev("tr('slots.your_networks')"));
|
||||
assert.doesNotMatch(card(a.ev), /slots\.|undefined|NaN|\{[a-z]+\}/, lang);
|
||||
assert.deepEqual(a.errors, [], lang);
|
||||
}
|
||||
});
|
||||
81
tests/scenarios-playtest.test.js
Normal file
81
tests/scenarios-playtest.test.js
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
// Rule C1, played (gameplay-rules): every handmade scenario has a reference strategy (scripts/lib/scenario-ref.js,
|
||||
// the player's own actions, a plan a sensible human would follow) that wins within its days, and the obvious shortcut
|
||||
// does not. The win days below were recorded in the 2.0.0 playtest; a balance change that moves them far is a change
|
||||
// in how the scenario plays, so look before you re-record.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
const { play } = require('../scripts/lib/scenario-ref');
|
||||
|
||||
const HIRE = ['hire', ['transit', 'routers', 'repair', 'sales', 'ix']];
|
||||
const home = (c) => [['bb', c], ['tr', c, 1], ['ix', c]];
|
||||
const GN_H = ['hire', ['transit', 'routers', 'repair', 'sales', 'ix', 'caches', 'pni']];
|
||||
const GN_REF = [['bb', 'icn'], ['ix', 'icn'], ['tr', 'icn', 1], ['pni', 'icn', 'ktt', 0], GN_H, ['served', 120], ['link', 'icn', 'tok', 1], ['tr', 'tok', 1], ['ix', 'tok'], ['last', 'icn'], ['pop', 'hkg']];
|
||||
// ref: the reference plan; win: [earliest, latest] day it may win on; cheese: the shortcut, and `by`, the day before
|
||||
// which it must not win (null: never within the scenario's days).
|
||||
const PLAY = {
|
||||
stg: { ref: [['bb', 'stg'], ['ix', 'stg'], ['link', 'stg', 'fra', 1], ['ix', 'fra'], ['bb', 'fra'], ['link', 'fra', 'ams', 1], ['ix', 'ams'], ['bb', 'ams'], ['link', 'ams', 'lon', 1], ['ix', 'lon'], ['bb', 'lon'], ['link', 'fra', 'par', 1], ['ix', 'par'], ['bb', 'par'], ['hire', ['routers', 'repair', 'caches', 'pni', 'ix', 'sales'], { pni: { paid: true } }], ['link', 'stg', 'muc', 1], ['ix', 'muc'], ['bb', 'muc'], ['wait', 120], ['pnis'], ['link', 'lon', 'nyc', 2], ['ix', 'nyc'], ['bb', 'nyc'], ['wait', 200], ['pnis']],
|
||||
win: [120, 240], cheese: [['bb', 'stg'], ['ix', 'stg'], ['link', 'stg', 'fra', 1], ['ix', 'fra'], ['bb', 'fra'], ['loans'], ['hire', ['routers', 'repair']]], by: null },
|
||||
// The other way round the planet: Paris, New York, Los Angeles, Tokyo, Hong Kong, Singapore.
|
||||
redsea: { ref: [...home('mrs'), ['link', 'mrs', 'par', 1], ['bb', 'par'], ['ix', 'par'], ['link', 'par', 'nyc', 1, 'amitie'], ['tr', 'nyc', 1], ['ix', 'nyc'], ['link', 'nyc', 'lax', 1], ['ix', 'lax'], ['tr', 'lax', 1], ['link', 'lax', 'tok', 1, 'jup'], ['bb', 'tok'], ['tr', 'tok', 1], ['ix', 'tok'], ['link', 'tok', 'hkg', 1, 'apg'], ['bb', 'hkg'], ['tr', 'hkg', 1], ['ix', 'hkg'], ['link', 'hkg', 'sin', 1], ['bb', 'sin'], ['tr', 'sin', 1], ['ix', 'sin'], HIRE],
|
||||
// 2.0.0: no more max-prefix outages to break the 30-day streak, so the reference can finish in under 100 days.
|
||||
win: [80, 250], cheese: [...home('mrs'), ['loans'], ['link', 'mrs', 'sin', 1], ['bb', 'sin']], by: null },
|
||||
spat: { ref: [...home('nyc'), HIRE], avoid: ['cog'], win: [50, 140], cheese: [...home('nyc'), ['hire', ['routers', 'repair']]], by: 160 },
|
||||
carnaval: { ref: [...home('rio'), ['hire'], ['wait', 69], ['prep', 'rio', 400], ['wait', 76], ['prep', 'rio', 400], ['wait', 83], ['prep', 'rio', 400]], win: [95, 95], cheese: [...home('rio'), ['loans']], by: null },
|
||||
darien: { ref: [...home('pan'), ['link', 'pan', 'bog', 1, 'pccs'], ['bb', 'bog'], ['ix', 'bog'], ['link', 'bog', 'lim', 1], ['bb', 'lim'], ['ix', 'lim'], ['link', 'lim', 'scl', 1], ['bb', 'scl'], ['ix', 'scl'], ['link', 'scl', 'sao', 1], ['bb', 'sao'], ['tr', 'sao', 1], ['ix', 'sao'], HIRE],
|
||||
win: [30, 90], cheese: [...['pan', 'bog', 'lim', 'scl', 'sao'].flatMap((c) => [['bb', c], ['tr', c, 1]]), ['hire']], by: null },
|
||||
c2c: { ref: [...home('cpt'), ['link', 'cpt', 'jnb', 1], ['bb', 'jnb'], ['tr', 'jnb', 1], ['ix', 'jnb'], ['link', 'jnb', 'nbo', 1], ['bb', 'nbo'], ['ix', 'nbo'], ['link', 'nbo', 'cai', 1], ['bb', 'cai'], ['ix', 'cai'], ['link', 'jnb', 'lag', 1], ['bb', 'lag'], ['ix', 'lag'], HIRE],
|
||||
win: [70, 200], cheese: [...home('cpt'), ['link', 'cpt', 'cai', 0], ['pop', 'lag'], ['pop', 'nbo'], ['hire']], by: null },
|
||||
ixbr: { ref: [...home('sao'), ...[['sao', 'rio', 1], ['sao', 'cpq', 0], ['sao', 'cwb', 0], ['cwb', 'poa', 0], ['rio', 'bhz', 0], ['bhz', 'bsb', 0], ['bsb', 'gyn', 0], ['rio', 'ssa', 0], ['ssa', 'rec', 0], ['rec', 'for', 0], ['rec', 'nat', 0], ['for', 'bel', 0], ['bel', 'mao', 0], ['bsb', 'cgb', 0], ['sao', 'vix', 0]].flatMap(([a, b, t]) => [['link', a, b, t], ['ix', b, 0]]), ['bb', 'rio'], ['tr', 'rio', 1], ['bb', 'bsb'], ['tr', 'bsb', 1], ['bb', 'for'], ['tr', 'for', 1], HIRE],
|
||||
win: [40, 120], cheese: [['bb', 'sao'], ['tr', 'sao', 1], ...['sao', 'rio', 'bsb', 'bhz', 'cwb', 'poa', 'for', 'rec', 'ssa', 'cpq', 'gyn', 'bel', 'mao', 'nat', 'vix', 'cgb'].flatMap((c) => [['pop', c], ['ix', c, 0]]), ['hire']], by: null },
|
||||
// Sender pays: Seoul transit to start (dear, but fast), one paid PNI with Kay-Tea for reach, then haul the bulk from
|
||||
// Tokyo and keep Seoul transit as the last resort. Seoul alone loses money on the sender-pays fee and never wins.
|
||||
gangnam: { ref: GN_REF, win: [130, 190], cheese: [...home('icn'), ['loans']], by: null },
|
||||
// Bigger routers bring Flowspec, which also takes floods: without a scrubbing center it takes twice as long.
|
||||
flood: { ref: [...home('ams'), ['scrub', 'ams', 1], ['tr', 'ams', 1], HIRE], win: [80, 200], cheese: [...home('ams'), ['tr', 'ams', 1], ['loans']], by: 180 },
|
||||
fttb: { ref: [...home('syd'), ['link', 'syd', 'akl', 0, 'tasman'], ['link', 'syd', 'nou', 0, 'gond'], ...['mel', 'bne', 'adl', 'per'].flatMap((c) => [['bb', c], ['tr', c, 1]]), ['link', 'syd', 'mel', 1], ['link', 'syd', 'bne', 1], ['link', 'mel', 'adl', 1], ['link', 'adl', 'per', 0], HIRE],
|
||||
win: [80, 200], cheese: [...['syd', 'mel', 'bne', 'adl', 'per'].map((c) => ['bb', c]), ['tr', 'syd', 1], ['link', 'syd', 'akl', 0, 'tasman'], ['link', 'syd', 'nou', 0, 'gond'], ['loans']], by: 60 },
|
||||
// Tallinn has no transit: over the water to Helsinki and Stockholm on two cables each way, and round by land to Riga.
|
||||
baltic: { ref: [['bb', 'tll'], ['ix', 'tll'], ['link', 'tll', 'hel', 1, 'balt'], ['tr', 'hel', 1], ['link', 'tll', 'sto', 1, 'balt'], ['tr', 'sto', 1], ['link', 'tll', 'hel', 1, 'elisa'], ['link', 'tll', 'rix', 1], ['tr', 'rix', 1], ['hire', ['transit', 'routers', 'repair', 'ix']]],
|
||||
win: [90, 200], cheese: [['bb', 'tll'], ['ix', 'tll'], ['loans']], by: null },
|
||||
// The 1.6T chains: grow the traffic first, then light every hop at once (a day-0 build also gets there, just).
|
||||
pac: { ref: [...home('hnl'), ...home('lax'), ...home('syd'), ['link', 'lax', 'tok', 1, 'jup'], HIRE, ['served', 145], ['link', 'lax', 'hnl', 4, 'seaus'], ['link', 'hnl', 'suv', 4, 'scx'], ['link', 'suv', 'syd', 4, 'scx']],
|
||||
win: [50, 120], cheese: [...home('hnl'), ...home('lax'), ...home('syd'), ['link', 'lax', 'tok', 1, 'jup'], ['link', 'lax', 'syd', 3, 'hwk'], ['loans']], by: null },
|
||||
atl: { ref: [['bb', 'pdl'], ['tr', 'pdl', 1], ...home('mia'), ...home('mad'), ...home('lis'), HIRE, ['link', 'mia', 'bda', 4, 'sol'], ['link', 'bda', 'pdl', 4, 'sol'], ['link', 'pdl', 'mad', 4, 'sol'], ['served', 90], ['link', 'lis', 'tci', 4, 'ace'], ['link', 'tci', 'lag', 4, 'twoaf'], ['bb', 'lag']],
|
||||
win: [40, 120], cheese: [['bb', 'pdl'], ['tr', 'pdl', 1], ...home('mia'), ...home('mad'), ...home('lis'), ['link', 'mia', 'mad', 3, 'col3'], ['link', 'lis', 'lag', 3, 'equi'], ['loans']], by: null },
|
||||
};
|
||||
|
||||
test('C1 played: every scenario has a reference strategy and a shortcut that fails', () => {
|
||||
const g = load();
|
||||
const ids = JSON.parse(g.ev('JSON.stringify(SCN.map(x=>x.id))'));
|
||||
assert.deepEqual(Object.keys(PLAY).sort(), ids.slice().sort(), 'C1: every scenario has a reference strategy here');
|
||||
});
|
||||
|
||||
for (const [id, P] of Object.entries(PLAY)) {
|
||||
test(`${id}: the reference wins in its days, the shortcut does not`, () => {
|
||||
const g = load();
|
||||
const r = play(g.ev, id, P.ref, { avoid: P.avoid });
|
||||
assert.ok(r.won !== null, `${id}: the reference does not win (${JSON.stringify(r)})`);
|
||||
assert.ok(r.won >= P.win[0] && r.won <= P.win[1] && (id === 'carnaval' || r.won <= r.limit * 0.75), `${id}: won on day ${r.won}, want ${P.win.join('-')} of ${r.limit}`);
|
||||
const c = play(g.ev, id, P.cheese, { days: P.by || undefined });
|
||||
assert.ok(c.won === null, `${id}: the shortcut wins on day ${c.won}${P.by ? ` (before day ${P.by})` : ''}`);
|
||||
assert.deepEqual(g.errors, []);
|
||||
});
|
||||
}
|
||||
|
||||
// Gangnam Style Peering bites every way (2.0.0 playtest): paying the sender-pays fee on everything loses money, hauling
|
||||
// everything from Tokyo is too slow for Korean users, and the old plan (transit everywhere, no Kay-Tea) has neither
|
||||
// the reach nor the profit. The reference's Seoul transit as first choice, not last resort, also stays in the red.
|
||||
for (const [name, plan] of Object.entries({
|
||||
'Seoul transit and Kay-Tea': [['bb', 'icn'], ['ix', 'icn'], ['tr', 'icn', 1], ['pni', 'icn', 'ktt', 0], GN_H],
|
||||
'everything from Tokyo': [['bb', 'icn'], ['link', 'icn', 'tok', 1], ['tr', 'tok', 1], ['ix', 'tok'], ['pni', 'tok', 'ktt', 0], ['pop', 'hkg'], GN_H],
|
||||
'the 1.x reference': [...home('icn'), ['link', 'icn', 'tok', 1], ['ix', 'tok'], ['tr', 'tok', 1], ['link', 'icn', 'hkg', 1], ['ix', 'hkg'], ['tr', 'hkg', 1], HIRE],
|
||||
'Tokyo haul, Seoul transit first': GN_REF.filter((s) => s[0] !== 'last'),
|
||||
})) {
|
||||
test(`gangnam: ${name} does not win`, () => {
|
||||
const g = load();
|
||||
const r = play(g.ev, 'gangnam', plan);
|
||||
assert.equal(r.won, null, `${name} won on day ${r.won}`);
|
||||
assert.deepEqual(g.errors, []);
|
||||
});
|
||||
}
|
||||
|
|
@ -9,6 +9,30 @@ function network(ev) {
|
|||
ev("const L=(a,b,t,v)=>{UI.via=v||null;openLinkModal(a,b);ACT.buildLink({tier:t});};L('fra','ams',3);L('fra','par',3);L('ams','lon',2,'uly');closeModal()");
|
||||
}
|
||||
|
||||
test('gaming offers and signed customers show their DDoS risk in Deals, city panels and customer lists', () => {
|
||||
const { ev, errors, dom } = load();
|
||||
ev("ACT.start({});S.cash=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.offers=['game','cgame','host'].map(type=>({id:type,city:'fra',name:type,bw:5,rate:100,reqs:[],exp:S.day+30,type}));UI.left='deals';UI.leftOpen=true;renderLeft()");
|
||||
const notes = (root, action) => {
|
||||
const buttons = [...root.querySelectorAll(`[data-act="${action}"]`)];
|
||||
assert.equal(buttons.length, 3);
|
||||
for (const button of buttons) {
|
||||
const id = JSON.parse(button.dataset.args).id;
|
||||
const count = (button.closest('.row').textContent.match(/Gaming attracts attacks/g)||[]).length;
|
||||
assert.equal(count, id==='game'||id==='cgame'?1:0, `risk note for ${id}`);
|
||||
}
|
||||
};
|
||||
assert.equal(ev('gamingCount()'), 0, 'offers disclose future risk before signing');
|
||||
notes(dom.window.document.getElementById('leftBody'), 'accept');
|
||||
ev("selectCity('fra');ACT.tab({t:'cust'})");
|
||||
notes(dom.window.document.getElementById('panelBody'), 'accept');
|
||||
ev("for(const id of ['game','cgame','host'])ACT.accept({id});UI.tab='cust';renderPanel()");
|
||||
assert.equal(ev('gamingCount()'), 2, 'the note uses the same customer classification as the attack calculation');
|
||||
notes(dom.window.document.getElementById('panelBody'), 'dropBiz');
|
||||
ev('ACT.custOpen({})');
|
||||
notes(dom.window.document.getElementById('custSec'), 'custGo');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('event networks pay in full when the crowd is served, nothing up front', () => {
|
||||
const { ev, errors } = load();
|
||||
seed(ev, 4);
|
||||
|
|
|
|||
170
tests/specialist.test.js
Normal file
170
tests/specialist.test.js
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// Specialist play (#187, #173): capability offers, vendor demo units, pioneer fiber, consortium seats, charters.
|
||||
const start = "ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})";
|
||||
const pop = (c) => `S.pops['${c}']=S.pops['${c}']||{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};`;
|
||||
const df = (id, a, b, ch, own = true) => `S.links.push({id:'${id}',a:'${a}',b:'${b}',kind:'df',own:${own},sys:'roadm',ch:${JSON.stringify(ch)},km:kmBetween('${a}','${b}'),sub:false,cable:null,mo:0,trench:'${id}',cut:0,day:0,ready:0,spares:false});`;
|
||||
// Spawn offers until one of a type shows up (or give up), with everything else cleared out of the way.
|
||||
const spawnUntil = (ev, type, n = 400) => ev(`(()=>{for(let i=0;i<${n};i++){S.offers=[];spawnOffer();const o=S.offers.find(o=>o.type==='${type}');if(o)return JSON.stringify(o);}return 'null';})()`);
|
||||
|
||||
test('#187 a capability brings its customers before the level does, only when you can serve them', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
ev(start);
|
||||
ev(`S.lvl=1;${pop('nyc')}${pop('chi')}compute()`);
|
||||
assert.equal(ev("spots().filter(s=>s.t==='hft').length"), 0, 'no low-latency path, no trading firm');
|
||||
assert.equal(JSON.parse(spawnUntil(ev, 'hft')), null, 'level 1 alone never brings HFT');
|
||||
ev("S.links.push({id:'w',a:'nyc',b:'chi',kind:'wave',tier:2,km:kmBetween('nyc','chi'),cut:0,mo:0});compute()");
|
||||
const s = JSON.parse(ev("JSON.stringify(spots().find(s=>s.t==='hft'))"));
|
||||
assert.deepEqual([s.a, s.b].sort(), ['chi', 'nyc']);
|
||||
const o = JSON.parse(spawnUntil(ev, 'hft'));
|
||||
assert.ok(o, 'the trading firm calls');
|
||||
assert.equal(o.bw, ev("BIZ_T.hft.opts[0]"), 'at the smallest size');
|
||||
assert.deepEqual(o.reqs, ['lat']);
|
||||
assert.ok(o.latMax >= s.n, 'and the path you have already meets it');
|
||||
assert.equal(o.spot.k, 'lat');
|
||||
ev("ACT.leftTab({t:'deals'});renderAll()");
|
||||
assert.match(dom.window.document.body.innerHTML, /They spotted your [\d.]+ ms (New York|Chicago)–(New York|Chicago) path/);
|
||||
// Lit dark fiber with enough capacity brings AI interconnects (level 4) to a level 3 network; not the bigger DCI.
|
||||
ev(`S.lvl=3;${df('d', 'nyc', 'chi', ['zr4', 'zr4'])}compute()`);
|
||||
const t = JSON.parse(ev("JSON.stringify([...new Set(spots().map(s=>s.t))])"));
|
||||
assert.ok(t.includes('ai'), 'AI training interconnect');
|
||||
assert.ok(!t.includes('hyper'), 'not a hyperscaler DCI three times its size');
|
||||
assert.ok(!t.includes('hft'), 'level 3 gets HFT anyway: no spotting needed');
|
||||
ev("S.lvl=5");
|
||||
assert.ok(!ev("spots().some(s=>s.t==='ai')"), 'once the level brings them, they are ordinary offers');
|
||||
assert.equal(ev("(()=>{S.rules.gates='open';const n=spots().length;S.rules.gates='ladder';return n;})()"), 0, 'open gates need no spotting');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#187 vendor demo units: one level ahead, a wait and a markup', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
ev('S.lvl=1');
|
||||
assert.equal(ev("RG[1].lvl"), 2);
|
||||
assert.equal(ev("techOk('rg',1,2)"), false);
|
||||
ev("ACT.demoAsk({k:'rg',id:2})");
|
||||
assert.equal(ev("demoAt('rg',2)"), null, 'never two levels ahead');
|
||||
ev("ACT.demoAsk({k:'rg',id:1})");
|
||||
const at = ev("demoAt('rg',1)");
|
||||
assert.equal(at - ev('S.day'), ev('leadDays(DEMO_DAYS)'), 'a short wait');
|
||||
ev("ACT.upRouter({city:'fra',g:1})");
|
||||
assert.equal(ev("S.pops.fra.rgen||0"), 0, 'not before it ships');
|
||||
ev(`S.day=${at}`);
|
||||
assert.equal(ev("techOk('rg',1,2)"), true);
|
||||
assert.equal(ev("swapCost('fra',1)"), ev("Math.round(RG[1].cost*hwMul('rt')*1.6)-tradeIn(0,1)"), '+60%');
|
||||
const cash = ev('S.cash');
|
||||
ev("ACT.upRouter({city:'fra',g:1})");
|
||||
assert.equal(ev("S.pops.fra.rgen"), 1);
|
||||
assert.ok(cash - ev('S.cash') > 0);
|
||||
// Optics and line systems the same way.
|
||||
ev("S.lvl=2;ACT.demoAsk({k:'opt',id:'zr8'});ACT.demoAsk({k:'sys',id:'roadm'})");
|
||||
assert.ok(ev("demoAt('opt','zr8')!==null&&demoAt('sys','roadm')!==null"));
|
||||
ev("S.day+=30");
|
||||
assert.equal(ev("optCost('zr8')"), ev("Math.round(OPT.zr8.cost*1.6*hwMul('opt'))"));
|
||||
assert.equal(ev("sysCost('roadm')"), ev("Math.round(DF_SYS.roadm.cost*1.6)"));
|
||||
ev('S.lvl=3');
|
||||
assert.equal(ev("optCost('zr8')"), ev("Math.round(OPT.zr8.cost*hwMul('opt'))"), 'list price once your level catches up');
|
||||
assert.equal(ev("demoCan(5)"), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#187 pioneer fiber: dig your own before level 3, at a markup', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
ev(`S.lvl=2;${pop('ams')}UI.dfSrc='build';UI.dfSys='lite';UI.pending={a:'fra',b:'ams'};`);
|
||||
const km = ev("kmBetween('fra','ams')");
|
||||
assert.equal(ev(`digCost(${km})`), ev(`Math.round(dfBuildCost(${km})*1.6)`));
|
||||
const cash = ev('S.cash');
|
||||
ev('ACT.orderDf()');
|
||||
const l = JSON.parse(ev("JSON.stringify(S.links.find(l=>l.kind==='df'))"));
|
||||
assert.ok(l && l.own, 'your own trench');
|
||||
assert.equal(cash - ev('S.cash'), ev(`digCost(${km})+DF_SYS.lite.cost+ampCount(${km})*AMP_COST`));
|
||||
ev('S.lvl=3');
|
||||
assert.equal(ev(`digCost(${km})`), ev(`dfBuildCost(${km})`), 'no markup at level 3');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#173 a consortium seat: offer, pay, build, light, cut, save', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
ev(start);
|
||||
ev("S.lvl=3;S.capDeal={at:S.day,c:'lon'};capDealTick(S.day)");
|
||||
const off = JSON.parse(ev('JSON.stringify(S.seatOff)'));
|
||||
assert.ok(off && ev(`SEAT_ROUTES.lon.some(r=>r[2]===${JSON.stringify(off.name)})`), 'a capacity conference offers a seat on one of its routes');
|
||||
ev("ACT.leftTab({t:'deals'});renderAll()");
|
||||
assert.match(dom.window.document.body.innerHTML, /Consortium seat: /);
|
||||
// A seat short enough to light with level 2 optics.
|
||||
ev("S.lvl=2;S.seatOff={a:'syd',b:'akl',name:'Tasman Devil',km:seatKm('syd','akl'),exp:S.day+30}");
|
||||
const km = ev('S.seatOff.km');
|
||||
const cash = ev('S.cash'), popC = ev("popCost('syd')+popCost('akl')");
|
||||
ev('ACT.seatBuy({n:2})');
|
||||
assert.equal(cash - ev('S.cash'), ev(`seatCost(${km},2)`) + popC, 'your share of the build, and the landing POPs');
|
||||
const l = JSON.parse(ev("JSON.stringify(S.links.find(l=>l.seat))"));
|
||||
assert.ok(l.own && l.sub && l.pairs === 2 && l.ready > ev('S.day'), 'your own subsea glass, being laid');
|
||||
assert.equal(ev('S.seatOff'), null);
|
||||
assert.equal(ev("pairsMax(S.links.find(l=>l.seat))"), 2, 'only the pairs you bought');
|
||||
// Save and load keep it.
|
||||
ev('const s=migrate(JSON.parse(JSON.stringify(S)));window.__s=s');
|
||||
assert.equal(ev("__s.links.find(l=>l.seat).pairs"), 2);
|
||||
// It lands and lights with your own optics.
|
||||
ev(`S.day=${l.ready};S.pops.syd.rgen=S.pops.akl.rgen=1;ACT.addCh({id:'${l.id}',o:'zr4'});compute()`);
|
||||
assert.ok(ev(`dfCap(S.links.find(l=>l.id==='${l.id}'))`) > 0, 'lit');
|
||||
ev(`ACT.subUpgrade({id:'${l.id}',k:'terminal'})`);
|
||||
assert.equal(ev(`S.links.find(l=>l.id==='${l.id}').subterminal`), undefined, 'the consortium owns the terminals');
|
||||
// A cut on the cable cuts your share.
|
||||
ev(`S.links=S.links.filter(l=>l.id==='${l.id}');eval('('+fireFailure.toString().replace('for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}}',\"type='cut';\")+')')()`);
|
||||
assert.ok(ev(`linkDown(S.links.find(l=>l.id==='${l.id}'))`), 'the cut takes your pairs down too');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#187 the Low-latency boutique: pick it on day 0, traders weigh more and pay more, Speed of Light wins', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
ev(start);
|
||||
ev("ACT.leftTab({t:'goals'});renderAll()");
|
||||
assert.match(dom.window.document.body.innerHTML, /Pick a charter/);
|
||||
ev("window.innerWidth=360;renderAll()");
|
||||
assert.match(dom.window.document.body.innerHTML, /Low-latency boutique/, 'on a phone too');
|
||||
ev("window.innerWidth=1280");
|
||||
assert.equal(ev('charter()'), 'global', 'Global backbone until you pick');
|
||||
ev("ACT.charter({k:'boutique'})");
|
||||
assert.equal(ev('charter()'), 'boutique');
|
||||
ev("ACT.charter({k:'global'})");
|
||||
assert.equal(ev('charter()'), 'boutique', 'picked once');
|
||||
// More and better-paid trading firms than a global backbone with the same network.
|
||||
const count = (k) => {
|
||||
const g = load();
|
||||
g.ev(start);
|
||||
g.ev(`S.lvl=2;S.charter='${k}';${pop('nyc')}${pop('chi')}compute()`);
|
||||
return JSON.parse(g.ev("(()=>{let n=0,r=0;for(let i=0;i<300;i++){S.offers=[];spawnOffer();const o=S.offers.find(o=>o.type==='hft');if(o){n++;if(o.reqs.length===1)r=o.rate/(150+kmBetween(o.city,o.city2)*0.08)/BIZ_T.hft.km;}}return JSON.stringify({n,r});})()"));
|
||||
};
|
||||
const gl = count('global'), bq = count('boutique');
|
||||
assert.ok(bq.n > gl.n * 1.5, `boutique traders call more (${bq.n} vs ${gl.n})`);
|
||||
assert.ok(Math.abs(bq.r - 1.4) < 0.02 && Math.abs(gl.r - 1) < 0.02, 'and pay 40% more');
|
||||
// Speed of Light: three finance routes faster on your own glass than any lease, and two paying latency customers.
|
||||
ev(`S.lvl=2;${pop('nyc')}${pop('chi')}${pop('ash')}${df('a', 'nyc', 'chi', ['zr4'])}${df('b', 'chi', 'ash', ['zr4'])}${df('c', 'nyc', 'ash', ['zr4'])}compute()`);
|
||||
assert.equal(ev('solRoutes().length'), 3);
|
||||
ev('specDay(S.day)');
|
||||
assert.equal(ev('S.solWon'), 0, 'not without paying customers');
|
||||
ev("for(const [a,b] of [['nyc','chi'],['chi','ash']])S.biz.push({id:uid(),city:a,city2:b,name:'T',type:'hft',bw:1,rate:1000,reqs:['lat'],latMax:latMaxOf(a,b),mood:100,since:0});compute();specDay(S.day)");
|
||||
assert.equal(ev('S.solWon'), Math.max(1, ev('S.day')), 'Speed of Light');
|
||||
ev('checkBadges()');
|
||||
assert.notEqual(ev("S.ach.sol"), undefined, 'and its badge');
|
||||
ev("renderAll()");
|
||||
assert.match(dom.window.document.body.innerHTML, /Won on /);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#187 old saves load as Global backbone; scenarios ignore charters', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
ev("const o=JSON.parse(JSON.stringify(S));for(const k of ['charter','chartSet','demo','seatOff','solWon'])delete o[k];o.links.push({id:'q',a:'fra',b:'ams',kind:'df',own:false,sub:false,seat:true,sys:'lite',ch:[],km:400,ready:0});window.__o=migrate(o)");
|
||||
assert.equal(ev('__o.charter'), 'global');
|
||||
assert.equal(ev('__o.chartSet'), true, 'no charter card for an old save');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(__o.demo)')), {});
|
||||
assert.equal(ev('__o.seatOff'), null);
|
||||
assert.equal(ev("__o.links.find(l=>l.id==='q').seat"), undefined, 'a forged seat is dropped');
|
||||
ev("S.charter='boutique';S.scn={id:'x'}");
|
||||
assert.equal(ev('charter()'), 'global');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -303,7 +303,7 @@ test('fast routing gives exactly the same result as the plain path it replaces',
|
|||
for(const c of cs)for(const x of ixIdsIn(c)){try{ACT.buyIx({city:x,tier:1});}catch(e){}if(S.dk&&S.dk.q){S.dk.q=null;closeModal();}if(S.ixp[x]!==undefined&&!S.rs[x])ACT.rs({city:x});}
|
||||
compute();for(const n of NETS)for(const c of cs)if(n.pops.includes(c)&&peerOk(n.id,'pni',c).ok&&S.pni.length<150)S.pni.push({id:'p'+n.id+c,net:n.id,city:c,tier:1,n:1});
|
||||
for(const n of NETS.filter(n=>n.cache))for(const c of cs.slice(0,15))for(const k of [1,2])S.caches.push({id:'c'+k+n.id+c,city:c,net:n.id,site:'a'});
|
||||
if(S.pni[3])S.pni[3].pref='high';if(S.transit[1])S.transit[1].pref='low';S.te={on:true,day:0};S.nextFail=1e9;S.nextEvent=1e9;`);
|
||||
if(S.pni[3])S.pni[3].pref='high';if(S.transit[1])S.transit[1].pref='low';S.te={on:true,day:0};S.core={lv:2,run:2,legacy:true};S.nextFail=1e9;S.nextEvent=1e9;`);
|
||||
const sig = () => ev(`JSON.stringify({served:R.served,demand:R.demand,reach:R.reach,peered:R.peered,teMoved:R.teMoved,egT:R.egT,
|
||||
srv:Object.keys(R.citySrv).sort().map(c=>[c,R.citySrv[c]]),load:S.links.map(l=>R.load[l.id]||0),node:Object.keys(R.nodeLoad).sort().map(c=>[c,R.nodeLoad[c]]),
|
||||
t:Object.keys(R.useT).sort().map(k=>[k,R.useT[k]]),p:Object.keys(R.usePni).sort().map(k=>[k,R.usePni[k]]),ix:Object.keys(R.useIx).sort().map(k=>[k,R.useIx[k]]),c:Object.keys(R.useCache).sort().map(k=>[k,R.useCache[k]])})`);
|
||||
|
|
@ -326,11 +326,11 @@ test('Auto-TE routes around a full link exactly like the plain path', () => {
|
|||
plainCompute(ev);
|
||||
// Frankfurt reaches its only upstream in Amsterdam over a 10G wave, or the long way through Brussels on 800G.
|
||||
ev(`ACT.start({});S.cash=1e12;S.lvl=13;for(const g of GOALS)S.done[g.id]=0;for(const c of ['ams','bru'])ACT.buildPop({city:c});
|
||||
for(const c of ['fra','ams','bru']){S.pops[c].rgen=RG.length-1;S.pops[c].routers=RMAX;}if(!S.pops.fra.bb)ACT.launchBB({city:'fra'});S.pops.fra.bb.d=CITY.fra.P*0.8;
|
||||
for(const c of ['fra','ams','bru']){S.pops[c].rgen=RG_TOP;S.pops[c].routers=RMAX;}if(!S.pops.fra.bb)ACT.launchBB({city:'fra'});S.pops.fra.bb.d=CITY.fra.P*0.8;
|
||||
const L=(a,b,t)=>{UI.via=null;UI.lmode='wave';UI.route='main';openLinkModal(a,b);ACT.buildLink({tier:t});closeModal();};
|
||||
L('fra','ams',0);L('fra','bru',3);L('bru','ams',3);
|
||||
S.transit=[];const t=NETS.find(n=>n.price&&n.pops.includes('ams')&&n.type==='t1');ACT.buyTransit({city:'ams',net:t.id,tier:3});
|
||||
S.ixp={};S.pni=[];S.caches=[];S.te={on:true,day:0};S.nextFail=1e9;S.nextEvent=1e9;`);
|
||||
S.ixp={};S.pni=[];S.caches=[];S.te={on:true,day:0};S.core={lv:2,run:2,legacy:true};S.nextFail=1e9;S.nextEvent=1e9;`);
|
||||
const sig = () => ev('JSON.stringify({served:R.served,teMoved:R.teMoved,egT:R.egT,load:S.links.map(l=>R.load[l.id]||0),node:R.nodeLoad,t:R.useT})');
|
||||
for (const script of ['', 'spill at 70%']) {
|
||||
ev(`S.te.script=${JSON.stringify(script)}`);
|
||||
|
|
|
|||
597
tests/standing-orders.test.js
Normal file
597
tests/standing-orders.test.js
Normal file
|
|
@ -0,0 +1,597 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// A small network with a hired intern, every order off, no cash floor and no fat fingers (Change Freeze).
|
||||
const BASE = "ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=3;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" +
|
||||
"ACT.launchBB({city:'fra'});S.pops.fra.bb.d=300;S.pops.fra.rgen=1;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()";
|
||||
function game(t, extra = '') {
|
||||
const h = load();
|
||||
t.after(() => h.dom.window.close());
|
||||
h.ev(BASE);
|
||||
if (extra) h.ev(extra);
|
||||
return h;
|
||||
}
|
||||
const hire = ev => ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal()");
|
||||
const on = (ev, k, p = {}, cap) => ev(`S.ops.on.${k}=true;S.ops.p.${k}=${JSON.stringify(p)};${cap === undefined ? '' : `S.ops.cap.${k}=${cap};`}`);
|
||||
const shift = ev => ev('opsDay(S.day)');
|
||||
const cash = ev => ev('S.cash');
|
||||
// The same game twice: the intern's shift in one, the player's own clicks in the other. Both must cost the same and end the same.
|
||||
function twins(t, extra, order, manual, pick) {
|
||||
const A = game(t), B = game(t);
|
||||
// Hire first: hiring recomputes, which would wipe any routing state the case stages.
|
||||
hire(A.ev); hire(B.ev);
|
||||
if (extra) { A.ev(extra); B.ev(extra); }
|
||||
order(A.ev);
|
||||
const a0 = cash(A.ev); shift(A.ev); const a1 = cash(A.ev);
|
||||
const b0 = cash(B.ev); B.ev(manual); const b1 = cash(B.ev);
|
||||
assert.ok(a0 - a1 > 0, 'the order did some paid work');
|
||||
assert.equal(a0 - a1, b0 - b1, 'the shift cost exactly what the clicks cost');
|
||||
if (pick) assert.equal(A.ev(pick), B.ev(pick), 'and left the network the same');
|
||||
assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []);
|
||||
return A;
|
||||
}
|
||||
|
||||
test('a new game has no intern and every order off; nothing runs and no random numbers are drawn', t => {
|
||||
const { ev, errors } = game(t);
|
||||
assert.equal(ev('S.ops.intern'), null);
|
||||
assert.equal(ev('Object.values(S.ops.on).some(Boolean)'), false);
|
||||
ev("for(const k in S.ops.on)S.ops.on[k]=true");
|
||||
const r = ev('window.__n=0;window.__r=Math.random;Math.random=()=>{__n++;return __r()};const s=JSON.stringify(S);opsDay(S.day);Math.random=__r;s===JSON.stringify(S)&&__n===0');
|
||||
assert.equal(r, true, 'no intern: orders never run, even switched on');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the intern is hired from customer level 2 (or with gates open), costs a monthly salary, and can be let go', t => {
|
||||
const { ev, errors } = game(t);
|
||||
ev("S.lvl=1;ACT.opsHire({id:'kevin'})");
|
||||
assert.equal(ev('S.ops.intern'), null, 'level 1: not yet');
|
||||
ev("S.rules=makeRules('sandbox');S.rules.preset='freeze';ACT.opsHire({id:'annie'})");
|
||||
assert.equal(ev('S.ops.intern'), 'annie', 'gates open');
|
||||
ev("S.ops.intern=null;S.rules=makeRules('freeze');S.lvl=2;compute()");
|
||||
const mo = ev('R.costMo'), c0 = cash(ev);
|
||||
ev("ACT.opsHire({id:'tracy'})");
|
||||
assert.equal(ev('S.ops.intern'), 'tracy');
|
||||
assert.equal(c0 - cash(ev), ev('INTERN_MO'), 'first month up front');
|
||||
assert.equal(ev('R.costMo') - mo, ev('INTERN_MO'), 'then a monthly salary');
|
||||
ev("ACT.opsFire();ACT.opsFire()");
|
||||
assert.equal(ev('S.ops.intern'), null);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('transit headroom adds a LAG member, exactly as the + member button would', t => {
|
||||
const A = twins(t, "S.transit[0].hist=[60,80,70]",
|
||||
ev => on(ev, 'transit', { x: 1.5 }),
|
||||
"ACT.lagT({id:S.transit[0].id,d:1})", "JSON.stringify(S.transit.map(t=>[t.net,t.tier,t.n||1]))");
|
||||
assert.match(A.ev('opsEntry(S.ops.log[0])'), /Kevin topped up transit in Frankfurt \+1×100G/);
|
||||
});
|
||||
|
||||
test('transit headroom buys a new port from a chosen provider and stops at the multiple', t => {
|
||||
const A = twins(t, "S.transit[0].hist=[100]",
|
||||
ev => on(ev, 'transit', { x: 2, prov: 'ntt' }),
|
||||
"ACT.buyTransit({city:'fra',net:'ntt',tier:1})", "JSON.stringify(S.transit.map(t=>[t.net,t.tier,t.n||1]))");
|
||||
assert.ok(A.ev("S.transit.reduce((a,t)=>a+lagCap(PORT[t.tier].g,t.n),0)") >= 200);
|
||||
});
|
||||
|
||||
test('routers: add one above the load level, as Add router would', t => {
|
||||
twins(t, "R.nodeLoad.fra=R.nodeCap.fra*0.85",
|
||||
ev => on(ev, 'routers', { at: 80, how: 'add' }),
|
||||
"ACT.addRouter({city:'fra'})", 'S.pops.fra.routers');
|
||||
});
|
||||
|
||||
test('routers: swap generation only where a second router carries the traffic', t => {
|
||||
const { ev, errors } = game(t, 'R.nodeLoad.fra=R.nodeCap.fra*0.95');
|
||||
hire(ev); on(ev, 'routers', { at: 80, how: 'swap' });
|
||||
shift(ev);
|
||||
assert.equal(ev('S.pops.fra.rgen'), 1, 'one router: a swap would be an outage, so no');
|
||||
ev('S.pops.fra.routers=2;compute();R.nodeLoad.fra=R.nodeCap.fra*0.95');
|
||||
const want = ev('swapCost("fra",mainRG(RG[1].cls+1))'), c0 = cash(ev);
|
||||
shift(ev);
|
||||
assert.equal(ev('S.pops.fra.rgen'), ev('mainRG(RG[1].cls+1)'));
|
||||
assert.equal(c0 - cash(ev), want, 'paid the swap price after trade-in');
|
||||
assert.equal(ev("S.inc.some(i=>i.type==='maint')"), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('caches: free boxes only once the network sends enough traffic locally', t => {
|
||||
const { ev, errors } = game(t);
|
||||
hire(ev);
|
||||
const best = ev("NETS.filter(n=>n.cache&&(R.demTo[n.id]||0)>=n.cache.min).map(n=>(R.cityDem.fra||0)*NSH[n.id]).sort((a,b)=>b-a)[0]||0");
|
||||
assert.ok(best > 0, 'some network qualifies for a cache in this game');
|
||||
on(ev, 'caches', { g: 50 });
|
||||
if (best < 50) { shift(ev); assert.equal(ev('S.caches.length'), 0, 'below the threshold: nothing'); }
|
||||
on(ev, 'caches', { g: 1 });
|
||||
const c0 = cash(ev);
|
||||
shift(ev);
|
||||
const want = JSON.parse(ev("JSON.stringify(utilityCaches('fra'))"));
|
||||
assert.ok(ev('S.caches.length') > 0);
|
||||
assert.equal(want.add.filter(x => ev(`(R.cityDem.fra||0)*NSH['${x.net}']`) >= 1).length, 0, 'every eligible box is in');
|
||||
assert.equal(cash(ev), c0, 'caches are free to rack');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('IX: weekly route servers and every willing peer, the same as the #192 batch', t => {
|
||||
const A = game(t, "ACT.buyIx({city:'fra',tier:0,signed:true});ACT.buyIx({city:'ams',tier:0})"), B = game(t, "ACT.buyIx({city:'fra',tier:0,signed:true});ACT.buyIx({city:'ams',tier:0})");
|
||||
hire(A.ev); on(A.ev, 'ix');
|
||||
A.ev('S.day=13');shift(A.ev);
|
||||
assert.equal(A.ev('Object.keys(S.rs).length'), 0, 'not on a weekday the intern skips');
|
||||
A.ev('S.day=14');shift(A.ev);
|
||||
B.ev('ACT.utilityRouteServers();ACT.utilityPeers()');
|
||||
assert.equal(A.ev('JSON.stringify(S.rs)'), B.ev('JSON.stringify(S.rs)'));
|
||||
assert.equal(A.ev('JSON.stringify(Object.keys(S.peers).sort())'), B.ev('JSON.stringify(Object.keys(S.peers).sort())'));
|
||||
assert.equal(A.ev('utilityPeers().reduce((n,r)=>n+r.requests.length,0)'), 0);
|
||||
assert.deepEqual(A.errors, []);
|
||||
});
|
||||
|
||||
test('PNI: weekly, big enough networks only, paid peering left out by default, at each network\'s own size and lead time', t => {
|
||||
const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;compute()");
|
||||
hire(ev); on(ev, 'pni', { g: 5, tier: 1 }, 0);
|
||||
ev('S.day=17;S.pops.fra.bb.d=3000;S.pops.ams.bb={d:3000};compute()');
|
||||
const plan = JSON.parse(ev("JSON.stringify(pniBatch(null,1).orders.filter(q=>(R.cityDem[q.city]||0)*NSH[q.net]>=5&&(NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).map(q=>({k:q.city+q.net,cost:q.cost,tier:q.tier,big:pniBig(q.net)})))"));
|
||||
assert.ok(plan.length > 0);
|
||||
const c0 = cash(ev);
|
||||
shift(ev);
|
||||
const got = JSON.parse(ev('JSON.stringify(S.pni.map(p=>({k:p.city+p.net,tier:p.tier,ready:p.ready})))'));
|
||||
assert.deepEqual(got.map(p => p.k).sort(), plan.map(p => p.k).sort());
|
||||
// Lead times are each network's own (pniLead), quick here under Change Freeze.
|
||||
for (const p of plan) { const g = got.find(x => x.k === p.k); assert.equal(g.tier, p.tier); assert.ok(g.ready > 17 && g.ready <= 17 + ev(p.big ? 'leadDays(365)' : 'leadDays(42)'), p.k); }
|
||||
assert.equal(c0 - cash(ev), plan.reduce((a, p) => a + p.cost, 0), 'the same setup fees as the bulk order');
|
||||
assert.equal(ev("S.pni.some(p=>NET[p.net].pol==='paid'&&!paidFree(NET[p.net]))"), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('sales: decline offers below the minimum, sign the ready ones with #185\'s trial', t => {
|
||||
const { ev, errors } = game(t);
|
||||
hire(ev); on(ev, 'sales', { acc: true, min: 5000 });
|
||||
ev('S.transit[0].tier=3;S.pops.fra.rgen=3;compute()');
|
||||
ev("S.offers=[{id:'tiny',city:'fra',name:'Tiny',type:'dia',bw:1,rate:600,reqs:[],exp:30},{id:'big',city:'fra',name:'Big',type:'dia',bw:10,rate:600,reqs:[],exp:30},{id:'gen',city:'fra',name:'Gen',type:'dia',bw:10,rate:600,reqs:['gen'],exp:30}]");
|
||||
shift(ev);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.biz.map(b=>b.id))')), ['big']);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))')), ['gen'], 'unmet requirements wait, the tiny one is gone');
|
||||
assert.match(ev('opsEntry(S.ops.log[0])'), /declined a tiny offer, signed a customer/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('repairs: rush what has a price, as the Rush repair button would', t => {
|
||||
twins(t, "S.links=[{id:'f',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,eqDown:10,mo:1}];S.inc=[{id:'amp',type:'amp',ref:'f',until:10,cost:3000,msg:'amp'}];S.pops.ams={day:0,bb:null,boost:0,down:0,routers:1,gen:false}",
|
||||
ev => on(ev, 'repair'), "ACT.fixInc({id:'amp'})", 'S.inc.length');
|
||||
});
|
||||
|
||||
test('optics: light hot fiber with the optic already in it, at the #177 batch price', t => {
|
||||
const extra = "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;S.links.push({id:'f',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,mo:1,trench:'f'});compute();R.load.f=dfCap(S.links.at(-1))*0.95";
|
||||
const A = twins(t, extra, ev => on(ev, 'optics', { at: 70 }),
|
||||
"ACT.setChCount({id:'f',o:'zr4',n:2})", "JSON.stringify(S.links.find(l=>l.id==='f').ch)");
|
||||
assert.equal(A.ev("S.links.find(l=>l.id==='f').ch.length"), 2, 'one more channel brings the fiber under the level');
|
||||
});
|
||||
|
||||
test('decommission: smaller parallel waves go once the bigger link has room, never one a customer needs', t => {
|
||||
const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;for(const [id,tier] of [['w1',0],['w2',0],['big',2]])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:450,sub:false,cut:0,mo:100,trench:id});compute()");
|
||||
hire(ev); on(ev, 'decom', { keep: true });
|
||||
ev("R.load={w1:1,w2:1,big:10}");
|
||||
shift(ev);
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id).sort())")), ['big', 'w1'], 'one small wave kept as a spare');
|
||||
on(ev, 'decom', { keep: false });
|
||||
ev("S.biz.push({id:'c',name:'C',type:'l2vpn',city:'fra',city2:'ams',bw:1,rate:1,reqs:['diverse'],mood:100,since:0});R.load={w1:1,big:10}");
|
||||
shift(ev);
|
||||
assert.ok(ev("S.links.some(l=>l.id==='w1')"), 'a diverse-path customer still needs it');
|
||||
ev("S.biz=[];R.load={w1:1,big:10}");
|
||||
shift(ev);
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id))")), ['big']);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the monthly budget cap and the cash floor stop the intern; a new month resets the budget', t => {
|
||||
const { ev, errors } = game(t);
|
||||
hire(ev); ev('S.transit[0].hist=[600]'); on(ev, 'transit', { x: 3 }, 10000);
|
||||
const c0 = cash(ev);
|
||||
shift(ev);
|
||||
const spent = c0 - cash(ev);
|
||||
assert.ok(spent > 0 && spent <= 10000, 'some work, never over the cap');
|
||||
assert.equal(ev('S.ops.spent.transit'), spent);
|
||||
assert.match(ev('opsEntry(S.ops.log[0])'), /stopped at the budget for Keep transit headroom/);
|
||||
const c1 = cash(ev);
|
||||
shift(ev);
|
||||
assert.equal(cash(ev), c1, 'the same month: nothing more');
|
||||
// The next step (four 100G members to 400G, $16k) never fits a $10k month; the budget still starts again.
|
||||
ev('S.day+=30;S.ops.cap.transit=50000');
|
||||
shift(ev);
|
||||
assert.ok(cash(ev) < c1, 'a new month, a new budget');
|
||||
assert.equal(ev('S.ops.spent.transit'), c1 - cash(ev), 'counted from zero');
|
||||
ev("S.ops.cap.transit=0;S.ops.floor=1e6;S.cash=1e6+500;S.transit[0].hist=[1e5]");
|
||||
const c2 = cash(ev);
|
||||
shift(ev);
|
||||
assert.equal(cash(ev), c2, 'the cash floor holds even without a cap');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('pause: an order switched off does nothing, and per-POP switches leave a city alone', t => {
|
||||
const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});ACT.buyTransit({city:'ams',net:'cog',tier:1});for(const t of S.transit)t.hist=[90]");
|
||||
hire(ev); on(ev, 'transit', { x: 2 });
|
||||
ev("ACT.opsToggle({k:'transit'})");
|
||||
const s0 = ev('JSON.stringify(S.transit)');
|
||||
shift(ev);
|
||||
assert.equal(ev('JSON.stringify(S.transit)'), s0);
|
||||
ev("ACT.opsToggle({k:'transit'});ACT.opsPop({k:'transit',city:'ams'});closeModal()");
|
||||
shift(ev);
|
||||
assert.ok(ev("(S.transit.find(t=>t.city==='fra').n||1)") > 1, 'Frankfurt topped up');
|
||||
assert.equal(ev("(S.transit.find(t=>t.city==='ams').n||1)"), 1, 'Amsterdam left alone');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the shift runs inside dayTick, respects a stopped clock, batches its work and recomputes once', t => {
|
||||
const { ev, errors } = game(t, "S.transit[0].hist=[60,80,70]");
|
||||
hire(ev); on(ev, 'transit', { x: 1.5 }); on(ev, 'caches', { g: 1 });
|
||||
const n = ev("window.__c=compute;window.__n=0;compute=()=>{__n++;return __c()};opsDay(S.day);compute=__c;__n");
|
||||
assert.equal(n, 1, 'one recompute for the whole shift');
|
||||
const d = ev('S.day');
|
||||
ev('dayTick()');
|
||||
assert.equal(ev('S.ops.log[0].d'), d + 1);
|
||||
ev("S.rules.clock=false;const before=JSON.stringify(S.ops);dayTick();window.__same=before===JSON.stringify(S.ops)");
|
||||
assert.equal(ev('__same'), true, 'no clock, no shift');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the NOC gets one notice a week, the shift report; the daily lines stay in the Ops sheet', t => {
|
||||
const { ev, errors } = game(t, "S.transit[0].hist=[600]");
|
||||
ev('S.day=14');
|
||||
hire(ev); on(ev, 'transit', { x: 1.5 }); on(ev, 'sales', { acc: true, min: 5000 });
|
||||
ev('S.transit[0].tier=3;S.pops.fra.rgen=3;compute()');
|
||||
const n0 = ev('S.log.length');
|
||||
for (let d = 14; d < 21; d++) {
|
||||
if (d === 15) ev("S.offers=[{id:'tiny',city:'fra',name:'Tiny',type:'dia',bw:1,rate:600,reqs:[],exp:60},{id:'big',city:'fra',name:'Big',type:'dia',bw:10,rate:600,reqs:[],exp:60}]");
|
||||
ev(`S.day=${d}`); shift(ev);
|
||||
}
|
||||
assert.equal(ev('S.log.length'), n0, 'a whole week of shifts: no NOC notice yet');
|
||||
assert.ok(ev('S.ops.log.length') >= 2, 'the Ops sheet has the daily detail');
|
||||
ev('S.day=21'); shift(ev);
|
||||
assert.equal(ev('S.log.length'), n0 + 1, 'one notice for the week');
|
||||
assert.match(ev('S.log[0].t'), /^Kevin's week Kevin signed a customer \(\+\$6\.0k\/mo\), topped up transit .*declined a tiny offer.*Week total: \$[\d.]+k up front, \+\$[\d.]+k\/mo\./);
|
||||
assert.equal(ev('S.log[0].k'), 'good');
|
||||
ev('S.day=22'); shift(ev);
|
||||
assert.equal(ev('S.log.length'), n0 + 1, 'and nothing more until the next week ends');
|
||||
// Only the sales order now: one tiny offer declined on day 23, reported when the week ends.
|
||||
ev("for(const k in S.ops.on)S.ops.on[k]=false;S.ops.on.sales=true;S.offers=[{id:'t2',city:'fra',name:'T2',type:'dia',bw:1,rate:600,reqs:[],exp:60}];S.day=23");shift(ev);
|
||||
ev("S.day=28");shift(ev);
|
||||
assert.equal(ev('S.log.length'), n0 + 2);
|
||||
assert.match(ev('S.log[0].t'), /declined a tiny offer\.$/, 'nothing spent: no money line');
|
||||
assert.equal(ev('S.log[0].k'), '');
|
||||
ev("S.day=35");shift(ev);
|
||||
assert.equal(ev('S.log.length'), n0 + 2, 'an idle week: no notice');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the Ops sheet opens with the intern\'s mood and the weekly shift report, at 360 px, in every language', t => {
|
||||
for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) {
|
||||
const h = load(lang === 'en' ? {} : { lang });
|
||||
const { ev, dom, errors } = h;
|
||||
ev(BASE); ev('S.day=14'); dom.window.innerWidth = 360;
|
||||
hire(ev);
|
||||
ev('opsModal()');
|
||||
const mood = () => dom.window.document.querySelector('#modalCard .ops-mood').textContent;
|
||||
assert.equal(mood(), ev("tr('ops.mood_new',{name:opsName()})"), lang + ': a new hire says so');
|
||||
on(ev, 'transit', { x: 1.5 }, 0);
|
||||
ev("S.transit[0].hist=[600];S.day=21");shift(ev);ev("S.transit[0].hist=[6000];S.day=28");shift(ev);ev('opsModal()');
|
||||
const reps = [...dom.window.document.querySelectorAll('#modalCard .ops-rep')];
|
||||
assert.equal(reps.length, 2, lang + ': last week, and this week so far');
|
||||
assert.equal(reps[0].lastElementChild.textContent, ev('opsWeekLine(S.ops.rep)'), lang);
|
||||
assert.ok(mood().length > 10, lang);
|
||||
assert.doesNotMatch(dom.window.document.getElementById('modalCard').textContent, /\bops\.[a-z_]+/, lang);
|
||||
assert.deepEqual(errors, [], lang);
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('the mood follows the week, with no dice', t => {
|
||||
const { ev, errors } = game(t);
|
||||
ev('S.day=100'); hire(ev); ev('S.day=110');
|
||||
const quiet = ev('opsMood()');
|
||||
assert.equal(ev('opsMood()'), quiet, 'the same day reads the same');
|
||||
assert.ok([ev("tr('ops.mood_quiet',{name:'Kevin'})"), ev("tr('ops.mood_kevin')")].includes(quiet));
|
||||
ev("S.ops.wk=opsWkNew(Math.floor(S.day/7));S.ops.wk.n.sales=1");
|
||||
assert.equal(ev('opsMood()'), ev("tr('ops.mood_sales',{name:'Kevin'})"));
|
||||
ev("S.ops.wk.n.broke=1;delete S.ops.wk.n.sales");
|
||||
assert.equal(ev('opsMood()'), ev("tr('ops.mood_broke',{name:'Kevin'})"));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('fat fingers: never under Change Freeze, rare and harmless in On-call and BGP at 3 a.m.', t => {
|
||||
const { ev, errors } = game(t);
|
||||
hire(ev);
|
||||
ev('window.__r=Math.random;Math.random=()=>0');
|
||||
for (let i = 0; i < 50; i++) shift(ev);
|
||||
assert.equal(ev('S.ops.log.some(e=>e.f!==undefined)'), false, 'Change Freeze: never, even on the unluckiest roll');
|
||||
for (const p of ['oncall', 'bgp']) {
|
||||
ev(`S.rules=makeRules('${p}');S.ops.log=[]`);
|
||||
const c0 = cash(ev), links = ev('S.links.length'), pops = ev('Object.keys(S.pops).length');
|
||||
shift(ev);
|
||||
assert.equal(ev('S.ops.log[0].f!==undefined'), true, p);
|
||||
assert.ok(c0 - cash(ev) <= 20000, 'costs a little at most');
|
||||
assert.equal(ev('S.links.length'), links); assert.equal(ev('Object.keys(S.pops).length'), pops);
|
||||
}
|
||||
ev('Math.random=__r');
|
||||
assert.ok(ev("OPS_FF_RATE.oncall<0.01&&OPS_FF_RATE.bgp<0.02"), 'rare');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a new POP from the template costs exactly the clicks it replaces', t => {
|
||||
const A = game(t), B = game(t);
|
||||
hire(A.ev); hire(B.ev);
|
||||
const q = JSON.parse(A.ev("JSON.stringify(opsTplQuote('ams'))"));
|
||||
assert.ok(q.net && q.ix && q.kit);
|
||||
const a0 = cash(A.ev); A.ev("ACT.opsNewPop({city:'ams'})"); const a1 = cash(A.ev);
|
||||
const b0 = cash(B.ev);
|
||||
B.ev(`ACT.buildPop({city:'ams'});ACT.launchBB({city:'ams'});ACT.buyTransit({city:'ams',net:'${q.net}',tier:0});ACT.buyIx({city:'ams',tier:0});ACT.utilityKit({city:'ams',cost:utilityKit('ams').cost})`);
|
||||
assert.equal(a0 - a1, q.cost, 'the quoted price');
|
||||
assert.equal(a0 - a1, b0 - cash(B.ev), 'the same as clicking it');
|
||||
assert.equal(A.ev('JSON.stringify([S.pops.ams.gen,S.pops.ams.site2,S.pops.ams.routers,!!S.pops.ams.bb,S.ixp.ams])'), B.ev('JSON.stringify([S.pops.ams.gen,S.pops.ams.site2,S.pops.ams.routers,!!S.pops.ams.bb,S.ixp.ams])'));
|
||||
A.ev('S.cash=10');A.ev("ACT.opsNewPop({city:'lon'})");
|
||||
assert.equal(A.ev('!!S.pops.lon'), false, 'all or nothing on the price');
|
||||
assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []);
|
||||
});
|
||||
|
||||
test('saves: old saves load with no intern and everything off, settings survive a reload, junk is repaired', t => {
|
||||
const { ev, errors } = game(t);
|
||||
ev("delete S.ops;S=migrate(JSON.parse(JSON.stringify(S)))");
|
||||
assert.equal(ev('S.ops.intern'), null);
|
||||
assert.equal(ev('Object.values(S.ops.on).some(Boolean)'), false);
|
||||
hire(ev);
|
||||
ev("on=1;S.ops.on.pni=true;S.ops.p.pni={g:50,tier:2,paid:true};S.ops.cap.pni=1e6;S.ops.skip.fra=['caches'];save();S=migrate(JSON.parse(slotRaw(UI.slot)))");
|
||||
assert.equal(ev("S.ops.intern==='kevin'&&S.ops.on.pni&&S.ops.p.pni.tier===2&&S.ops.cap.pni===1e6&&S.ops.skip.fra[0]==='caches'"), true);
|
||||
ev(`S.ops={intern:'mallory',on:{transit:'yes',hack:true},p:{transit:{x:99,prov:'nobody'}},cap:{transit:-5},spent:{transit:'lots'},skip:{atlantis:['transit'],fra:['ix','transit']},
|
||||
log:[{d:1,i:'kevin',r:[['transit',2,['fra +1×100G','<img>']],['evil',1,[]]],f:99,c:'fra'},'junk'],floor:3,tpl:{bb:'no'}};S=migrate(S)`);
|
||||
assert.equal(ev('S.ops.intern'), null);
|
||||
assert.equal(ev("S.ops.on.transit===false&&!('hack' in S.ops.on)"), true);
|
||||
assert.equal(ev("opsP('transit','x')===1.5&&opsP('transit','prov')==='cheap'&&opsCap('transit')===50000&&S.ops.spent.transit===0"), true);
|
||||
assert.equal(ev("JSON.stringify(S.ops.skip)"), '{"fra":["transit"]}');
|
||||
assert.equal(ev("JSON.stringify(S.ops.log)"), '[{"d":1,"i":"kevin","r":[["transit",2,["fra +1×100G"]]]}]');
|
||||
assert.equal(ev('S.ops.floor===50000&&S.ops.tpl.bb===true'), true);
|
||||
ev(`S.ops.wk={w:3,i:'kevin',n:{sales:2,evil:9,transit:'x'},wh:{transit:['fra +1×100G','<b>']},up:-5,mo:'a',rev:41000,ff:99};S.ops.rep={i:'mallory'};S=migrate(S)`);
|
||||
assert.equal(ev("JSON.stringify(S.ops.wk)"), '{"w":3,"i":"kevin","n":{"sales":2},"wh":{"transit":["fra +1×100G"]},"up":0,"mo":0,"rev":41000,"ff":7}');
|
||||
assert.equal(ev('S.ops.rep'), null);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the Ops sheet works at 360 px in every language, from the NOC tab and the phone tab bar', t => {
|
||||
for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) {
|
||||
const h = load(lang === 'en' ? {} : { lang });
|
||||
const { ev, dom, errors } = h;
|
||||
ev(BASE);
|
||||
dom.window.innerWidth = 360;
|
||||
const doc = dom.window.document;
|
||||
ev("ACT.phoneTab({t:'noc'})");
|
||||
const open = doc.querySelector('#leftBody [data-act="opsOpen"]');
|
||||
assert.ok(open, lang);
|
||||
open.click();
|
||||
const hireBtn = doc.querySelector('#modalCard [data-act="opsHire"]');
|
||||
assert.ok(hireBtn, lang);
|
||||
hireBtn.click();
|
||||
assert.ok(ev('opsHired()'), lang);
|
||||
doc.querySelector('#modalCard [data-act="opsToggle"]').click();
|
||||
assert.equal(doc.querySelector('#modalCard [data-act="opsToggle"]').getAttribute('aria-pressed'), 'true', lang);
|
||||
doc.querySelector('#modalCard [data-act="opsParam"]').click();
|
||||
const txt = doc.getElementById('modalCard').textContent;
|
||||
assert.doesNotMatch(txt, /\bops\.[a-z_]+/, lang);
|
||||
assert.ok(doc.querySelector('#modalCard select[data-chg="opsCity"]'), lang);
|
||||
ev("closeModal();selectCity('ams')");
|
||||
assert.ok(doc.querySelector('#panelBody [data-act="opsNewPop"]'), lang);
|
||||
assert.doesNotMatch(doc.getElementById('panelBody').textContent, /\bops\.[a-z_]+/, lang);
|
||||
assert.deepEqual(errors, [], lang);
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('sales trial at most one offer a shift, and an offer that did not fit waits a week', t => {
|
||||
const { ev, errors } = game(t);
|
||||
hire(ev); on(ev, 'sales', { acc: true, min: 0 });
|
||||
ev("S.offers=['a','b','c'].map(id=>({id,city:'fra',name:id,type:'dia',bw:1e5,rate:600,reqs:[],exp:60}));window.__t=0;window.__a=autoOffer;autoOffer=o=>{__t++;return __a(o)}");
|
||||
shift(ev);
|
||||
assert.equal(ev('__t'), 1, 'one routing trial per shift');
|
||||
for (let i = 0; i < 2; i++) { ev('S.day++'); shift(ev); }
|
||||
assert.equal(ev('__t'), 3, 'each offer once');
|
||||
ev('S.day++'); shift(ev);
|
||||
assert.equal(ev('__t'), 3, 'too big for the network: not tried again within the week');
|
||||
ev('S.day+=7'); shift(ev);
|
||||
assert.equal(ev('__t'), 4);
|
||||
ev('autoOffer=__a');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('re-hiring in a later month starts on a fresh budget, not last month\'s spending', t => {
|
||||
const { ev, errors } = game(t);
|
||||
hire(ev);
|
||||
ev("S.ops.spent.transit=50000;ACT.opsFire();ACT.opsFire();S.day=400;ACT.opsHire({id:'kevin'});closeModal()");
|
||||
assert.equal(ev('S.ops.spent.transit'), 0);
|
||||
assert.equal(ev('S.ops.mon'), ev('Math.floor(S.day/30)'));
|
||||
ev("S.ops.spent.transit=1234;ACT.opsFire();ACT.opsFire();ACT.opsHire({id:'annie'});closeModal()");
|
||||
assert.equal(ev('S.ops.spent.transit'), 1234, 'the same month: what was spent stays spent');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('transit never comes from a provider that breaks a promise: no-Cogentle customers, bank covenants, the Spat', t => {
|
||||
const { ev, errors } = game(t, "S.transit=[];ACT.buyTransit({city:'fra',net:'lvl',tier:0});compute();S.transit[0].hist=Array(30).fill(200)");
|
||||
hire(ev); on(ev, 'transit', { x: 1.5 });
|
||||
assert.equal(ev("cheapestTransit('fra').id"), 'cog', 'Cogentle is the cheapest here, so it would be the pick');
|
||||
ev("S.biz.push({id:'b1',city:'fra',name:'X',type:'dia',bw:1,rate:100,mood:100,since:S.day,reqs:['nocog']})");
|
||||
assert.equal(ev("reqOk(S.biz[0])"), true);
|
||||
shift(ev);
|
||||
assert.ok(ev('S.transit.length') > 1 || ev('S.transit[0].n') > 1, 'the intern still topped up');
|
||||
assert.equal(ev("S.transit.some(t=>t.net==='cog')"), false);
|
||||
assert.equal(ev("reqOk(S.biz[0])"), true, 'the customer still gets what they signed for');
|
||||
ev("S.ops.p.transit={x:1.5,prov:'cog'}");
|
||||
assert.notEqual(ev("opsProv('fra').id"), 'cog', 'even when the player picked Cogentle');
|
||||
assert.notEqual(ev("opsTplQuote('ams').net"), 'cog', 'and the new-POP template too');
|
||||
// A bank covenant says the same.
|
||||
ev("S.biz=[];S.loans=[{bank:'db',covs:['nocog'],pay:1,bal:1}]");
|
||||
assert.notEqual(ev("cheapestTransit('fra').id"), 'cog');
|
||||
// Cogentle is not speaking to Goggle: the Spat scenario, or a de-peering.
|
||||
ev("S.loans=[]");
|
||||
assert.equal(ev("cheapestTransit('fra').id"), 'cog');
|
||||
ev("S.ev.depeer=S.day+5");
|
||||
assert.notEqual(ev("cheapestTransit('fra').id"), 'cog');
|
||||
ev("S.ev.depeer=0;S.scn={id:'spat',rules:{spat:true}}");
|
||||
assert.notEqual(ev("cheapestTransit('fra').id"), 'cog');
|
||||
// Two upstreams: once met, never undone (adding is fine; the order never removes).
|
||||
ev("S.scn=null;S.biz=[{id:'b2',city:'fra',name:'Y',type:'dia',bw:1,rate:1,mood:100,since:0,reqs:['twoup']}]");
|
||||
assert.ok(ev("cheapestTransit('fra')"));
|
||||
ev("S.transit=[]");
|
||||
assert.equal(ev("cheapestTransit('fra')"), undefined, 'a lone first upstream would break "two upstreams"');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('decommission keeps its spare in another trench than the big link', t => {
|
||||
const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;for(const [id,tier,tr] of [['big',2,'T1'],['s1',1,'T1'],['s2',0,'T2']])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:400,sub:false,cut:0,mo:100,trench:tr});compute()");
|
||||
hire(ev); on(ev, 'decom', { keep: true });
|
||||
ev("R.load={big:1,s1:0,s2:0}");
|
||||
shift(ev);
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id).sort())")), ['big', 's2'], 'the 100G in the same trench goes, the 10G in its own trench stays');
|
||||
// Every small wave shares the big one's trench: keep the largest, as before.
|
||||
ev("S.links=S.links.filter(l=>l.id==='big');for(const [id,tier] of [['a',1],['b',0]])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:400,sub:false,cut:0,mo:100,trench:'T1'});compute();R.load={big:1}");
|
||||
shift(ev);
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id).sort())")), ['a', 'big']);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('decommission sees the traffic of a customer signed earlier in the same shift', t => {
|
||||
const { ev, errors } = game(t, "S.pops.fra.bb.d=30;ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;for(const [id,tier,tr] of [['big',2,'T1'],['s1',1,'T2'],['s2',1,'T3']])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:400,sub:false,cut:0,mo:1000,trench:tr});compute()");
|
||||
hire(ev); on(ev, 'sales', { acc: true, min: 0 }); on(ev, 'decom', { keep: false });
|
||||
ev("S.offers=[{id:'o1',city:'fra',city2:'ams',name:'Bulk Co',type:'l2vpn',bw:450,rate:20,reqs:[],exp:S.day+20}]");
|
||||
shift(ev);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.biz.map(b=>b.id))')).length, 1, 'signed');
|
||||
assert.equal(ev('S.links.length'), 3, 'its 450G needs every wave, so none goes');
|
||||
ev('compute()');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(bizWhy(S.biz[0]))')), []);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('no recompute on a shift that only declined offers or stopped at a budget', t => {
|
||||
const { ev, errors } = game(t);
|
||||
hire(ev); on(ev, 'sales', { acc: false, min: 50000 }); on(ev, 'transit', { x: 3 }, 10000);
|
||||
ev("S.ops.spent.transit=10000;S.transit[0].hist=[600];S.offers=[{id:'tiny',city:'fra',name:'Tiny',type:'dia',bw:1,rate:600,reqs:[],exp:30}]");
|
||||
const n = ev("window.__c=compute;window.__n=0;compute=()=>{__n++;return __c()};opsDay(S.day);compute=__c;__n");
|
||||
assert.equal(n, 0, 'nothing in the network changed');
|
||||
assert.match(ev('opsEntry(S.ops.log[0])'), /declined a tiny offer, stopped at the budget/);
|
||||
ev("S.ops.spent.transit=0");
|
||||
assert.equal(ev("window.__n=0;compute=()=>{__n++;return __c()};opsDay(S.day);compute=__c;__n"), 1, 'a real job still recomputes once');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('per-POP exceptions go with the POP: on decommission, and in a save that lost it', t => {
|
||||
const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});ACT.buildPop({city:'lon'});compute()");
|
||||
hire(ev);
|
||||
ev("ACT.opsPop({k:'transit',city:'ams'});ACT.opsPop({k:'caches',city:'lon'});closeModal()");
|
||||
ev("decommission(['ams'])");
|
||||
assert.equal(ev('JSON.stringify(S.ops.skip)'), '{"lon":["caches"]}');
|
||||
ev("ACT.buildPop({city:'ams'});closeModal()");
|
||||
assert.equal(ev("opsHere('transit','ams')"), true, 'a rebuilt POP starts with every order on');
|
||||
ev("S.ops.skip.par=['transit'];S=migrate(JSON.parse(JSON.stringify(S)))");
|
||||
assert.equal(ev('JSON.stringify(S.ops.skip)'), '{"lon":["caches"]}', 'no POP in Paris: its exception is dropped on load');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('one order that throws is paused and noted; the rest of the shift and the day still run', t => {
|
||||
const { ev, errors } = game(t, "S.transit[0].hist=[60,80,70]");
|
||||
hire(ev); on(ev, 'repair'); on(ev, 'transit', { x: 1.5 });
|
||||
ev("window.__r=OPS_RUN.repair;OPS_RUN.repair=()=>{throw new Error('boom')};window.__e=console.error;console.error=()=>{}");
|
||||
const d = ev('S.day'), saves = ev("window.__s=0;window.__sv=save;save=()=>{__s++;return __sv()};S.day=29;dayTick();save=__sv;__s");
|
||||
ev("OPS_RUN.repair=__r;console.error=__e");
|
||||
assert.ok(d >= 0 && saves >= 1, 'dayTick reached the save on day 30');
|
||||
assert.equal(ev('S.ops.on.repair'), false, 'the broken order is paused');
|
||||
assert.ok(ev("(S.transit[0].n||1)") > 1, 'the next order still ran');
|
||||
assert.match(ev('opsEntry(S.ops.log[0])'), /got stuck on Rush repairs and paused it/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the fat-fingered LAG member respects a paused transit order and per-POP exceptions', t => {
|
||||
const { ev, errors } = game(t);
|
||||
hire(ev);
|
||||
// Each shift rolls: fat finger yes, the only POP, the LAG slip (index 3).
|
||||
ev("S.rules=makeRules('bgp');window.__r=Math.random;window.__k=0;Math.random=()=>[0,0,0.7][__k++%3]");
|
||||
const n0 = ev('S.transit[0].n||1'), c0 = cash(ev);
|
||||
shift(ev);
|
||||
assert.equal(ev('__k'), 3);
|
||||
assert.equal(ev('S.ops.log[0].f'), 0, 'transit order paused: a harmless label instead');
|
||||
assert.equal(ev('S.transit[0].n||1'), n0); assert.equal(cash(ev), c0);
|
||||
on(ev, 'transit', { x: 1 }); ev("ACT.opsPop({k:'transit',city:'fra'});closeModal();S.transit[0].hist=[0]");
|
||||
shift(ev);
|
||||
assert.equal(ev('S.ops.log[0].f'), 0, 'Frankfurt excepted: the same');
|
||||
ev("ACT.opsPop({k:'transit',city:'fra'});closeModal()");
|
||||
shift(ev);
|
||||
assert.equal(ev('S.ops.log[0].f'), 3, 'allowed: the extra member');
|
||||
assert.equal(ev('S.transit[0].n||1'), n0 + 1);
|
||||
ev('Math.random=__r');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('caches: the cash floor and a running-cost budget hold; the panel and the log show what a month costs', t => {
|
||||
const { ev, errors } = game(t);
|
||||
hire(ev); on(ev, 'caches', { g: 1 });
|
||||
const add = () => ev("utilityCaches('fra').add.filter(x=>(R.cityDem.fra||0)*NSH[x.net]>=1).length");
|
||||
assert.ok(add() >= 2, 'several boxes on offer');
|
||||
ev('S.ops.floor=50000;S.cash=1000');
|
||||
shift(ev);
|
||||
assert.equal(ev('S.caches.length'), 0, 'below the floor: no new rent either');
|
||||
assert.match(ev('opsEntry(S.ops.log[0])'), /stopped at the budget for Accept free caches/);
|
||||
ev('S.cash=1e8;S.ops.cap.caches=1000');
|
||||
const m0 = ev('opsMoNow()');
|
||||
shift(ev);
|
||||
assert.equal(ev('S.caches.length'), 2, 'a $1k/mo budget fits two $400/mo boxes');
|
||||
assert.equal(ev('S.ops.addMo.caches'), 800);
|
||||
assert.equal(ev('opsMoNow()') - m0, 800);
|
||||
assert.equal(ev('S.ops.log[0].mo'), 800);
|
||||
assert.match(ev('opsEntry(S.ops.log[0])'), /racked 2 free caches \(Frankfurt\).*Cost: \$0 up front, \+\$800\/mo\./);
|
||||
ev('opsModal()');
|
||||
const txt = ev("document.getElementById('modalCard').textContent");
|
||||
assert.match(txt, /each box costs \$400\/mo/);
|
||||
assert.match(txt, /Adds at most: \+\$1\.0k\/mo/);
|
||||
assert.match(txt, /This month: \$0 up front, \+\$800\/mo on the bill/);
|
||||
ev('S.day+=30;S.ops.cap.caches=0'); shift(ev);
|
||||
assert.equal(ev('S.ops.addMo.caches'), (ev('S.caches.length') - 2) * 400, 'a new month counts from zero');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('transit: the log line and budget line show the monthly cost a top-up adds', t => {
|
||||
const { ev, errors } = game(t, "S.transit[0].hist=[60,80,70]");
|
||||
hire(ev); on(ev, 'transit', { x: 1.5 });
|
||||
const m0 = ev('opsMoNow()'), c0 = cash(ev);
|
||||
shift(ev);
|
||||
const mo = ev('opsMoNow()') - m0;
|
||||
assert.ok(mo > 0);
|
||||
assert.equal(ev('S.ops.log[0].up'), c0 - cash(ev));
|
||||
assert.equal(ev('S.ops.log[0].mo'), Math.round(mo));
|
||||
assert.equal(ev('Math.round(S.ops.addMo.transit)'), Math.round(mo));
|
||||
assert.match(ev('opsEntry(S.ops.log[0])'), /Cost: \$[\d.]+k up front, \+\$[\d.]+k?\/mo\./);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#226 the shift report\'s Open button in the NOC opens the Ops sheet, and survives a reload', t => {
|
||||
const { ev, errors, dom } = game(t);
|
||||
ev('S.day=14'); hire(ev); on(ev, 'sales', { acc: false, min: 5000 });
|
||||
ev("S.offers=[{id:'t',city:'fra',name:'T',type:'dia',bw:1,rate:600,reqs:[],exp:60}];S.day=15"); shift(ev);
|
||||
ev('S.day=21'); shift(ev);
|
||||
assert.match(ev('S.log[0].t'), /^Kevin's week/);
|
||||
ev("S=migrate(JSON.parse(JSON.stringify(S)));closeModal();ACT.leftTab({t:'noc'})");
|
||||
const doc = dom.window.document;
|
||||
const b = doc.querySelector(`#leftBody [data-act=logOpen][data-args='${JSON.stringify({ id: ev('S.log[0].id') })}']`);
|
||||
assert.ok(b, 'the report has an Open button');
|
||||
b.click();
|
||||
assert.equal(doc.getElementById('modal').hidden, false, 'a sheet opened');
|
||||
assert.ok(doc.querySelector('#modalCard .ops-rep'), 'and it is the Ops sheet with the report');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#228 the intern names the exchanges it peered at, even one that shares its city\'s id', t => {
|
||||
const { ev, errors } = game(t, "ACT.buyIx({city:'fra',tier:0,signed:true})");
|
||||
hire(ev); on(ev, 'ix');
|
||||
ev('S.day=14'); shift(ev);
|
||||
const line = ev('opsLine(S.ops.log[0])');
|
||||
// Frankfurt's first exchange has the city's id: the line names DE-KICKS, not the city
|
||||
assert.match(line, /peered with \d+ networks? at DE-KICKS/, line);
|
||||
assert.doesNotMatch(line, /at Frankfurt/);
|
||||
// two exchanges in two cities read as two exchanges, in the daily line and in the week's report
|
||||
const e = "{i:'kevin',r:[['peer',2,['fra~3','lon']]],up:0,mo:0}";
|
||||
assert.match(ev(`opsLine(${e})`), /at Apfelwein-IX, LYNX/);
|
||||
assert.match(ev("opsWeekLine({w:2,i:'kevin',n:{peer:2},wh:{peer:['fra~3','lon']},up:0,mo:0,rev:0,ff:0})"), /at Apfelwein-IX, LYNX/);
|
||||
// other orders still name cities
|
||||
assert.match(ev("opsLine({i:'kevin',r:[['routers',1,['lon +1']]],up:0,mo:0})"), /London \+1/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -4,7 +4,7 @@ const { load } = require('./harness');
|
|||
|
||||
function setup(ev) {
|
||||
ev(`ACT.start({});S.cash=1e11;S.lvl=13;S.day=100;for(const g of GOALS)S.done[g.id]=0;
|
||||
S.links=[{id:'cable',a:'lag',b:'bde',kind:'df',own:true,sub:true,sys:'roadm',km:7000,ch:[],day:100,ready:1000,cut:0,mo:1}];`);
|
||||
S.links=[{id:'cable',a:'lag',b:'bde',kind:'df',own:true,sub:true,sys:'roadm',km:15000,ch:[],day:100,ready:1000,cut:0,mo:1}];`);
|
||||
}
|
||||
|
||||
function dates(ev) {
|
||||
|
|
@ -55,7 +55,7 @@ test('packages included in the original order stay aligned with its accelerated
|
|||
const { ev, dom } = load();
|
||||
try {
|
||||
setup(ev);
|
||||
ev("S.won=true;UI.pending={a:'lag',b:'bde'};UI.seaterminal=UI.seaengineering=true;ACT.orderCable();S.links=[S.links.at(-1)]");
|
||||
ev("S.won=true;UI.pending={a:'sin',b:'lax'};UI.seaterminal=UI.seaengineering=true;ACT.orderCable();S.links=[S.links.at(-1)]");
|
||||
assert.equal(ev('S.links[0].subterminal'), ev('S.links[0].ready'));
|
||||
assert.equal(ev('S.links[0].subengineering'), ev('S.links[0].ready'));
|
||||
ev("ACT.crews({id:S.links[0].id})");
|
||||
|
|
@ -129,11 +129,11 @@ test('one-click completion costs the same as repeated crew hires and advances pe
|
|||
const button = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')].find(b => JSON.parse(b.dataset.args).all);
|
||||
assert.ok(button && !button.disabled, 'one-click option is available');
|
||||
const cash = ev('S.cash');
|
||||
assert.ok(button.textContent.includes(ev('fmt$(30*Math.round(15000+7000*6))')), 'full price is shown before purchase');
|
||||
assert.ok(button.textContent.includes(ev('fmt$(30*Math.round(15000+15000*6))')), 'full price is shown before purchase');
|
||||
button.click();
|
||||
const bulkDates = dates(ev), bulkCash = ev('S.cash');
|
||||
assert.deepEqual(bulkDates, [101, 131, 281]);
|
||||
assert.equal(cash - bulkCash, 30 * 57000);
|
||||
assert.equal(cash - bulkCash, 30 * 105000);
|
||||
const after = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')];
|
||||
assert.ok(after.every(b => b.disabled), 'both options stop at one day');
|
||||
ev("ACT.crews({id:'cable',all:1})");
|
||||
|
|
@ -150,18 +150,18 @@ test('one-click completion is atomic when unaffordable and handles short or comp
|
|||
const { ev, dom } = load();
|
||||
try {
|
||||
setup(ev);
|
||||
ev("S.cash=30*57000-1;UI.sel={type:'link',id:'cable'};renderPanel()");
|
||||
ev("S.cash=30*105000-1;UI.sel={type:'link',id:'cable'};renderPanel()");
|
||||
const bulk = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')].find(b => JSON.parse(b.dataset.args).all);
|
||||
assert.equal(bulk.disabled, true);
|
||||
ev("ACT.crews({id:'cable',all:1})");
|
||||
assert.equal(ev('S.cash'), 30 * 57000 - 1);
|
||||
assert.equal(ev('S.cash'), 30 * 105000 - 1);
|
||||
assert.equal(ev('S.links[0].ready'), 1000, 'no partial purchase');
|
||||
ev("S.cash=57000;S.links[0].ready=102;ACT.crews({id:'cable',all:1})");
|
||||
ev("S.cash=105000;S.links[0].ready=102;ACT.crews({id:'cable',all:1})");
|
||||
assert.equal(ev('S.cash'), 0);
|
||||
assert.equal(ev('S.links[0].ready'), 101, 'two days remaining costs one normal hire');
|
||||
assert.match(dom.window.document.body.textContent, /Construction is 1 day ahead\./);
|
||||
ev("S.cash=57000;S.day=101;ACT.crews({id:'cable',all:1})");
|
||||
assert.equal(ev('S.cash'), 57000, 'completed construction cannot be rushed');
|
||||
ev("S.cash=105000;S.day=101;ACT.crews({id:'cable',all:1})");
|
||||
assert.equal(ev('S.cash'), 105000, 'completed construction cannot be rushed');
|
||||
ev("S.day=100;S.links[0].ready=1000;S.links[0].own=false;ACT.crews({id:'cable',all:1})");
|
||||
assert.equal(ev('S.links[0].ready'), 1000, 'leased handovers cannot buy construction crews');
|
||||
} finally { dom.window.close(); }
|
||||
|
|
|
|||
197
tests/tier1-cone.test.js
Normal file
197
tests/tier1-cone.test.js
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
// Tier 1 by customer cone (#85): peering with every Tier 1 reaches their customers and their customers' customers,
|
||||
// so the long tail stops mattering for the win; networks in nobody's cone still need peering of their own.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// A transit-free network in Frankfurt with a PNI to every Tier 1 it needs.
|
||||
const t1Club = (ev) => {
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;delete S.done.t1;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=500");
|
||||
ev("S.transit=[];S.ixp={};S.peers={};S.pni=[];S.grace=null;for(const n of t1Need())S.pni.push({id:'p'+n.id,net:n.id,city:'fra',tier:2});compute()");
|
||||
};
|
||||
|
||||
test('cones are built once at load and hold customers of customers', () => {
|
||||
const { ev, errors } = load();
|
||||
assert.equal(ev("CONE.voc.includes('ddo')&&CONE.voc.includes('spn')"), true, 'Hocus Pocus brings its own customers');
|
||||
// Doodoo buys from Hocus Pocus, which buys from Not That Telecom: two levels down
|
||||
assert.equal(ev("NET.ddo.up.includes('voc')&&NET.voc.up.includes('ntt')"), true);
|
||||
assert.equal(ev("CONE_S.ntt.has('ddo')"), true, 'the Tier 1 cone is transitive');
|
||||
assert.equal(ev("CONE.ntt[0]"), 'ntt', 'a network is first in its own cone');
|
||||
assert.equal(ev("PNI_NETS===CONE"), true);
|
||||
assert.equal(ev("ANC.ddo[0]"), 'voc', 'nearest upstream first');
|
||||
assert.equal(ev("NETS.filter(n=>n.tail).every(n=>n.up&&n.up.length&&n.up.every(u=>NET[u]))"), true, 'the long tail buys transit');
|
||||
assert.equal(ev("NETS.filter(n=>n.tail).every(n=>ANC[n.id].some(u=>NET[u].type==='t1'))"), true, 'from a Tier 1, directly or through a carrier');
|
||||
assert.equal(ev("NET.tail45.up.join()"), 'mag', 'Auckland has no Tier 1: Hobbit Hole buys from a carrier that is there');
|
||||
assert.equal(ev("NETS.filter(n=>n.tail).map(n=>n.up.join('+')).join()"), ev("NETS.filter(n=>n.tail).map(n=>tailUp(n.name,n.pops).join('+')).join()"), 'stable: picked by name');
|
||||
// Australia's big ISPs buy only from Australian carriers, so a Tier 1 PNI is no back door to them.
|
||||
assert.equal(ev("['opt','tpr','abb','npt','lpt','lnt','pnt','stb','blg','inp'].some(id=>t1Need().some(t=>CONE_S[t.id].has(id)))"), false);
|
||||
// The smaller ones that buy from a Tier 1 or a carrier of one do come along, and these are exactly the ones.
|
||||
const au = "NETS.filter(n=>n.type==='eye'&&n.pops.length&&n.pops.every(c=>CITY[c].au)&&t1Need().some(t=>CONE_S[t.id].has(n.id))).map(n=>n.id).sort().join()";
|
||||
assert.equal(ev(au), 'ddo,ext,spn,tail44', 'Doodoo, Lintel, Spin2wintel, Kangaroo Courier');
|
||||
assert.equal(ev("[NET.tail44.name,NET.tail44.up.join(),NET.ddo.up.join(),NET.spn.up.join(),NET.ext.up.join(),NET.voc.up.join(),NET.spl.up.join()].join('|')"), 'Kangaroo Courier|cog|voc|voc|spl|ntt,tly|tly');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a transit-free network with PNIs to every Tier 1 reaches the long tail through their cones', () => {
|
||||
const { ev, errors } = load();
|
||||
t1Club(ev);
|
||||
const tail = ev("NETS.find(n=>n.tail&&n.pops.includes('akl')).id");
|
||||
for (const id of ['tail0', 'tail38', tail, 'sky', 'kys', 'tim']) {
|
||||
assert.equal(ev(`!!R.reachable.${id}`), true, `${id} is reachable`);
|
||||
assert.equal(ev(`!!R.nt.${id}`), true, `${id} without transit`);
|
||||
assert.equal(ev(`!!R.cone.${id}`), true, `${id} through a peer's cone`);
|
||||
}
|
||||
// the traffic really goes over the PNI with the upstream, not some made-up exit
|
||||
const up = ev("NET.tail0.up[0]");
|
||||
assert.ok(ev("(R.netEg.tail0||{}).p") > 0, 'over a PNI');
|
||||
assert.ok(ev(`R.usePni['p${up}']`) > 0, 'the PNI with its upstream carries it');
|
||||
// the traceroute shows the hand-off to the customer and an AS path one hop longer
|
||||
const tr = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'tail0'}))"));
|
||||
assert.match(tr.text, /hands it to its customer/);
|
||||
assert.equal(tr.asPath.length, 3, 'you, the Tier 1, the customer');
|
||||
assert.equal(tr.asPath[1], ev(`NET.${up}.asn`), 'through the upstream it buys transit from');
|
||||
assert.match(tr.why, /customers come after direct peers/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a network in nobody\'s cone still needs reaching directly', () => {
|
||||
const { ev, errors } = load();
|
||||
t1Club(ev);
|
||||
// Doitsche Telekomm buys from no one: no Tier 1 PNI reaches it
|
||||
assert.equal(ev("(NET.dtk.up||[]).length"), 0);
|
||||
assert.equal(ev("R.reachable.dtk"), false);
|
||||
assert.equal(ev("isTier1()"), false);
|
||||
assert.match(ev('t1Why()'), /nobody you peer with sells transit to/);
|
||||
// peer with every island directly and the win comes
|
||||
ev("for(const n of NETS)if(!R.reachable[n.id])S.pni.push({id:'i'+n.id,net:n.id,city:n.pops[0],tier:0});for(const n of NETS)if(n.pops.length&&!S.pops[n.pops[0]])S.pops[n.pops[0]]={day:0,bb:null,boost:0,down:0,routers:1,gen:false};compute()");
|
||||
assert.ok(ev("R.reach") > 0.999, `reach ${ev('R.reach')}`);
|
||||
assert.equal(ev("isTier1()"), true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the long tail no longer stands between you and Tier 1', () => {
|
||||
const { ev, errors } = load();
|
||||
t1Club(ev);
|
||||
// peer directly only with the networks in nobody's cone, never with the long tail itself
|
||||
ev("for(const n of NETS)if(!R.reachable[n.id]){if(!S.pops[n.pops[0]])S.pops[n.pops[0]]={day:0,bb:null,boost:0,down:0,routers:1,gen:false};S.pni.push({id:'i'+n.id,net:n.id,city:n.pops[0],tier:0});}compute()");
|
||||
assert.equal(ev("S.pni.some(p=>NET[p.net].tail)"), false, 'no session with any long-tail network');
|
||||
assert.equal(ev("NETS.filter(n=>n.tail).every(n=>R.reachable[n.id])"), true);
|
||||
assert.equal(ev("isTier1()"), true);
|
||||
// the peers you need directly are all real networks of some size, and fewer than before
|
||||
const islands = ev("S.pni.filter(p=>p.id[0]==='i').length");
|
||||
assert.ok(islands < 70, `${islands} networks to peer with directly`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a peer\'s cone comes after direct peering and before transit, so peering widely still pays', () => {
|
||||
const { ev, errors } = load();
|
||||
t1Club(ev);
|
||||
ev("ACT.buyTransit({city:'fra',net:'cog',tier:2});S.pni=S.pni.filter(p=>p.net!=='cog');compute()");
|
||||
// a Cogentle customer is reached through another Tier 1's cone only if it buys from one; transit is the fallback
|
||||
const id = ev("NETS.find(n=>n.tail&&n.up.length===1&&n.up[0]==='tly').id");
|
||||
assert.ok(ev(`(R.netEg.${id}||{}).p`) > 0, 'over the PNI with its upstream, not over transit');
|
||||
assert.equal(ev(`(R.netEg.${id}||{}).t||0`), 0);
|
||||
// a direct session beats the cone: peer with it at the exchange and its traffic moves there
|
||||
ev(`S.pops.fra.bb.d=500;ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'});compute()`);
|
||||
if (ev(`ixSessions('fra').has('${id}')`)) {
|
||||
assert.ok(ev(`(R.netEg.${id}||{}).ix`) > 0, 'direct peering wins over the cone');
|
||||
assert.equal(ev(`(R.netEg.${id}||{}).p||0`), 0);
|
||||
}
|
||||
// an IX session also brings the member's customers along
|
||||
assert.equal(ev("ixSessions('fra').has('gsl')"), true);
|
||||
const down = ev("DOWN.gsl.find(id=>!t1Need().some(t=>CONE_S[t.id].has(id))&&!ixSessions('fra').has(id))||''");
|
||||
if (down) assert.equal(ev(`R.reachable.${down}`), true, `${down} comes along with Glowball Sakura Lager's session`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('old saves keep their win: cones only ever add reach', () => {
|
||||
const { ev, errors } = load();
|
||||
t1Club(ev);
|
||||
ev("for(const n of NETS)if(!R.reachable[n.id]){if(!S.pops[n.pops[0]])S.pops[n.pops[0]]={day:0,bb:null,boost:0,down:0,routers:1,gen:false};S.pni.push({id:'i'+n.id,net:n.id,city:n.pops[0],tier:0});}compute()");
|
||||
ev("S.won=true;S.done.t1=S.day;S.t1Now=true");
|
||||
// a save from before 2.0, with an older Tier 1 set and no record of cones, loads and is still Tier 1
|
||||
ev("const o=JSON.parse(JSON.stringify(S));o.t1v=2;S=migrate(o);compute()");
|
||||
assert.equal(ev("S.won"), true);
|
||||
assert.equal(ev("isTier1()"), true);
|
||||
assert.equal(ev("tierLabel()"), 'Tier 1');
|
||||
// and reach with cones is never lower than reach without: every exit still reaches what it did
|
||||
const before = ev("R.reach");
|
||||
ev("for(const id of NET_IDS){CONE_S[id]=new Set([id]);DOWN[id]=[];}compute()");
|
||||
assert.ok(ev("R.reach") <= before + 1e-9, 'switching cones off can only lose reach');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the Road to Tier 1 card and the network list explain the cone, on a phone too', () => {
|
||||
for (const w of [1280, 360]) {
|
||||
const { ev, dom, errors } = load();
|
||||
ev(`window.innerWidth=${w}`);
|
||||
t1Club(ev);
|
||||
ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderLeft()");
|
||||
const txt = dom.window.document.getElementById('leftBody').textContent;
|
||||
assert.match(txt, /Road to Tier 1/);
|
||||
assert.match(txt, /their customers come along for free/);
|
||||
assert.match(txt, /\d+ networks already come along with a peer/);
|
||||
ev("ACT.netFocus({id:'tail0'})");
|
||||
assert.match(dom.window.document.getElementById('leftBody').textContent, /Reached through the customer cone of/);
|
||||
ev("S.pni=[];compute();ACT.netFocus({id:'tail0'})");
|
||||
assert.match(dom.window.document.getElementById('leftBody').textContent, /Buys transit from .*Peer with/);
|
||||
assert.match(ev("GOALS.find(g=>g.id==='t1').d"), /customers come along for free/);
|
||||
assert.deepEqual(errors, [], `${w}px`);
|
||||
}
|
||||
});
|
||||
|
||||
test('routing with cones costs about what it did: exits are asked once, cones are built at load', () => {
|
||||
const { ev, errors } = load();
|
||||
t1Club(ev);
|
||||
ev("for(const n of NETS.filter(n=>!n.tail&&!n.cn).slice(0,40))for(const c of ['fra','ams','lon']){if(!S.pops[c])S.pops[c]={day:0,bb:{d:400},boost:0,down:0,routers:4,gen:true};S.pni.push({id:n.id+c,net:n.id,city:c,tier:2});}compute()");
|
||||
const t = ev("(()=>{for(let i=0;i<3;i++)compute();const a=performance.now();for(let i=0;i<10;i++)compute();return (performance.now()-a)/10;})()");
|
||||
const plain = ev(`(()=>{const keep={};for(const id of NET_IDS){keep[id]=[CONE_S[id],DOWN[id]];CONE_S[id]=new Set([id]);DOWN[id]=[];}
|
||||
for(let i=0;i<3;i++)compute();const a=performance.now();for(let i=0;i<10;i++)compute();const r=(performance.now()-a)/10;for(const id of NET_IDS){CONE_S[id]=keep[id][0];DOWN[id]=keep[id][1];}return r;})()`);
|
||||
assert.ok(t < plain * 2 + 20, `compute() with cones ${t.toFixed(1)} ms vs without ${plain.toFixed(1)} ms`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the panel names the peer that really carries a network, not the first Tier 1 it buys from', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=50");
|
||||
// a long-tail network that buys from Cogentle first and Level Tree second; peer only with Level Tree
|
||||
const t = ev("NETS.find(n=>n.tail&&n.up.length===2&&n.up[0]==='cog'&&n.up[1]==='lvl').id");
|
||||
ev("S.transit=[];S.ixp={};S.peers={};S.grace=null;S.pni=[{id:'pl',net:'lvl',city:'fra',tier:2}];compute()");
|
||||
assert.equal(ev(`R.cone.${t}`), 'lvl');
|
||||
ev(`UI.left='goals';UI.leftOpen=true;ACT.netFocus({id:'${t}'})`);
|
||||
const txt = dom.window.document.getElementById('leftBody').textContent;
|
||||
assert.match(txt, /Reached through the customer cone of Level Tree/);
|
||||
assert.doesNotMatch(txt, /customer cone of Cogentle/);
|
||||
// over an exchange: the member you have a session with
|
||||
ev("S.pni=[];compute()");
|
||||
assert.equal(ev(`!!R.cone.${t}`), false);
|
||||
assert.match(ev(`(ACT.netFocus({id:'${t}'}),document.getElementById('leftBody').textContent)`), /Buys transit from Cogentle/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a traceroute down a two-level cone shows every network on the way', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=50");
|
||||
// Doodoo buys from Hocus Pocus, which buys from Not That Telecom; a PNI with Not That Telecom only
|
||||
ev("S.transit=[];S.ixp={};S.peers={};S.grace=null;S.pni=[{id:'pn',net:'ntt',city:'fra',tier:2}];compute()");
|
||||
const tr = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'ddo'}))"));
|
||||
assert.deepEqual(tr.asPath, [ev('S.asn'), ev('NET.ntt.asn'), ev('NET.voc.asn'), ev('NET.ddo.asn')]);
|
||||
assert.match(tr.text, /Not That Telecom hands it to its customer Hocus Pocus/);
|
||||
assert.match(tr.text, /Hocus Pocus hands it to its customer Doodoo/);
|
||||
assert.equal(ev("coneChain('ntt','ddo').join()"), 'ntt,voc,ddo');
|
||||
assert.equal(ev("R.cone.ddo"), 'ntt');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#114 Only Spätzle-IX still takes more than the exchange and two Tier 1 PNIs, now that cones count', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("UI.pitched=true;beginGame('T','stg',{scn:SCN.find(x=>x.id==='stg')});S.cash=1e9;S.lvl=10;S.pops.stg.bb={d:400};S.ixp.stg=0;for(const id of ixMembers('stg'))S.peers[id+'@stg']=1;compute()");
|
||||
const reach = (ts) => ev(`S.pni=[];for(const t of ${JSON.stringify(ts)})S.pni.push({id:'p'+t,net:t,city:'stg',tier:2});compute();R.reach`);
|
||||
const T = ['lvl', 'ntt', 'tly', 'cog', 'tat'];
|
||||
const goal = ev("SCN.find(x=>x.id==='stg').ok.toString()");
|
||||
assert.match(goal, /R\.reach>=0\.5/);
|
||||
for (let i = 0; i < T.length; i++) for (let j = i + 1; j < T.length; j++)
|
||||
assert.ok(reach([T[i], T[j]]) < 0.5, `${T[i]}+${T[j]} is not enough`);
|
||||
assert.ok(reach(['lvl', 'ntt', 'tly']) >= 0.5, 'three Tier 1 PNIs and the exchange can be');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
86
tests/useless-subsea-upgrades.test.js
Normal file
86
tests/useless-subsea-upgrades.test.js
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// #198: submarine upgrades that change nothing on a cable can't be bought.
|
||||
function cable(ev, km) {
|
||||
ev(`ACT.start({});S.cash=1e11;S.lvl=13;S.day=100;S.won=true;for(const g of GOALS)S.done[g.id]=0;
|
||||
S.links=[{id:'c',a:'atn',b:'syd',kind:'df',own:true,sub:true,sys:'roadm',km:${km},ch:['tp16'],day:0,ready:50,cut:0,mo:1}];
|
||||
UI.sel={type:'link',id:'c'};renderPanel()`);
|
||||
}
|
||||
const installBtn = (dom, k) => dom.window.document.querySelector(`#panelBody [data-act=subUpgrade][data-args*="${k}"]`);
|
||||
|
||||
test('#198 upgrades that do nothing on a long Pacific cable are disabled and refused', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
try {
|
||||
cable(ev, 17500); // about Atlanta to Sydney: 400G per channel with or without upgrades
|
||||
for (const k of ['terminal', 'engineering']) {
|
||||
assert.equal(installBtn(dom, k).disabled, true, `${k} button disabled`);
|
||||
const cash = ev('S.cash');
|
||||
ev(`ACT.subUpgrade({id:'c',k:'${k}'})`);
|
||||
assert.equal(ev('S.cash'), cash, `${k}: no charge`);
|
||||
assert.equal(ev(`S.links[0].sub${k}`), undefined, `${k}: not installed`);
|
||||
}
|
||||
assert.match(dom.window.document.getElementById('panelBody').textContent, /Makes no difference on this cable/);
|
||||
assert.deepEqual(errors, []);
|
||||
} finally { dom.window.close(); }
|
||||
});
|
||||
|
||||
test('#198 upgrades that only help together stay buyable, and one made useless by the other is not', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
try {
|
||||
cable(ev, 15000); // each alone: 400G, both: 800G
|
||||
assert.equal(installBtn(dom, 'terminal').disabled, false);
|
||||
assert.equal(installBtn(dom, 'engineering').disabled, false);
|
||||
ev("ACT.subUpgrade({id:'c',k:'terminal'})");
|
||||
assert.ok(ev('S.links[0].subterminal') > 0, 'terminal bought');
|
||||
ev('renderPanel()');
|
||||
assert.equal(installBtn(dom, 'engineering').disabled, false, 'engineering finishes the job');
|
||||
ev("ACT.subUpgrade({id:'c',k:'engineering'})");
|
||||
assert.ok(ev('S.links[0].subengineering') > 0, 'engineering bought');
|
||||
|
||||
cable(ev, 20000); // terminal lights it; engineering adds nothing once terminal is in
|
||||
ev("ACT.subUpgrade({id:'c',k:'terminal'});renderPanel()");
|
||||
assert.ok(ev('S.links[0].subterminal') > 0);
|
||||
assert.equal(installBtn(dom, 'engineering').disabled, true);
|
||||
ev("ACT.subUpgrade({id:'c',k:'engineering'})");
|
||||
assert.equal(ev('S.links[0].subengineering'), undefined);
|
||||
assert.deepEqual(errors, []);
|
||||
} finally { dom.window.close(); }
|
||||
});
|
||||
|
||||
test('#198 ordering a cable: useless upgrades can not be picked, and stale picks are not charged', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
try {
|
||||
ev("ACT.start({});S.cash=1e11;S.lvl=13;S.won=true;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'lon'});ACT.buildPop({city:'nyc'});UI.lmode='df';UI.dfSrc='cable';UI.seaDesign='standard';openLinkModal('lon','nyc')");
|
||||
// A transatlantic cable already runs every optic at its long-haul best.
|
||||
const btn = k => dom.window.document.querySelector(`#modalCard [data-act=seaPackage][data-args*="${k}"]`);
|
||||
assert.equal(btn('terminal').disabled, true);
|
||||
assert.equal(btn('engineering').disabled, true);
|
||||
ev("ACT.seaPackage({k:'terminal'})");
|
||||
assert.equal(ev('!!UI.seaterminal'), false, 'refused');
|
||||
// Picks left over from a longer route (or a different design) neither show as picked nor get charged.
|
||||
ev("UI.seaterminal=true;UI.seaengineering=true;ACT.seaDesign({v:'standard'})");
|
||||
assert.equal(btn('terminal').textContent.includes('✓'), false);
|
||||
assert.equal(btn('engineering').textContent.includes('✓'), false);
|
||||
const cash = ev('S.cash'), cost = ev("seaQuote('lon','nyc','standard').cost");
|
||||
ev('ACT.orderCable()');
|
||||
assert.equal(cash - ev('S.cash'), cost, 'no upgrade charged');
|
||||
assert.deepEqual(errors, []);
|
||||
} finally { dom.window.close(); }
|
||||
});
|
||||
|
||||
test('#198 ordering a transpacific cable: both upgrades help together, and the redundant one of a pair drops out', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
try {
|
||||
ev("ACT.start({});S.cash=1e11;S.lvl=13;S.won=true;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'sin'});ACT.buildPop({city:'lax'});UI.lmode='df';UI.dfSrc='cable';ACT.ownCab();UI.pending={a:'sin',b:'lax'};openLinkModal('sin','lax')");
|
||||
const km = ev("seaQuote('sin','lax','standard').km");
|
||||
assert.ok(km > 14000 && km < 17000, 'a route where only both upgrades together beat 400G');
|
||||
ev("ACT.seaPackage({k:'terminal'});ACT.seaPackage({k:'engineering'})");
|
||||
assert.equal(ev('!!UI.seaterminal&&!!UI.seaengineering'), true, 'both picked');
|
||||
assert.equal(ev("JSON.stringify(seaUps(seaQuote('sin','lax','standard').km))"), '{"terminal":true,"engineering":true}');
|
||||
// At 20,000 km either one alone lights the cable, so a pair keeps only the cheaper terminals.
|
||||
assert.equal(ev("JSON.stringify(seaUps(20000))"), '{"terminal":true,"engineering":false}');
|
||||
assert.deepEqual(errors, []);
|
||||
} finally { dom.window.close(); }
|
||||
});
|
||||
120
tests/utilities-caches.test.js
Normal file
120
tests/utilities-caches.test.js
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
function setup(t) {
|
||||
const h = load();
|
||||
t.after(() => h.dom.window.close());
|
||||
h.ev("ACT.start({});S.cash=1e8;UI.speed=0;for(const g of GOALS)S.done[g.id]=0;compute()");
|
||||
return h;
|
||||
}
|
||||
|
||||
test('kit balances each provider with minimal moves while buying the missing hardware', t => {
|
||||
const { ev, errors } = setup(t);
|
||||
ev("for(const [net,n] of [['cfl',4],['ggl',3]])for(let i=0;i<n;i++)S.caches.push({id:net+i,city:'fra',net});S.pops.ams={day:0,routers:1};S.caches.push({id:'elsewhere',city:'ams',net:'cfl',site:'b'});compute()");
|
||||
const before = ev('S.cash'), ids = ev('S.caches.map(c=>c.id).join()');
|
||||
const quote = JSON.parse(ev("JSON.stringify(utilityKit('fra'))"));
|
||||
assert.equal(quote.moves.length, 3);
|
||||
ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})");
|
||||
assert.equal(ev('S.cash'), before - quote.cost);
|
||||
assert.equal(ev("S.caches.filter(c=>c.city==='fra'&&c.net==='cfl'&&c.site==='b').length"), 2);
|
||||
assert.equal(ev("S.caches.filter(c=>c.city==='fra'&&c.net==='ggl'&&c.site==='b').length"), 1);
|
||||
assert.equal(ev("S.caches.find(c=>c.id==='elsewhere').site"), 'b');
|
||||
assert.equal(ev('S.caches.map(c=>c.id).join()'), ids);
|
||||
assert.equal(ev("utilityKit('fra').moves.length"), 0);
|
||||
const stable = ev('JSON.stringify(S.caches)');
|
||||
ev("ACT.utilityKit({city:'fra',cost:0})");
|
||||
assert.equal(ev('JSON.stringify(S.caches)'), stable);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('an already equipped PoP can balance caches for free, even with negative cash', t => {
|
||||
const { ev, errors } = setup(t);
|
||||
ev("Object.assign(S.pops.fra,{gen:true,site2:true,routers:3});for(const [net,site] of [['cfl','a'],['ggl','b']])for(let i=0;i<4;i++)S.caches.push({id:net+i,city:'fra',net,site});S.cash=-1;compute();selectCity('fra');ACT.tab({t:'links'})");
|
||||
assert.equal(ev("utilityKit('fra').moves.length"), 4, 'overall counts match but provider counts do not');
|
||||
assert.equal(ev("document.querySelector('#panelBody [data-act=utilityKit]').disabled"), false);
|
||||
ev("document.querySelector('#panelBody [data-act=utilityKit]').click()");
|
||||
assert.equal(ev('S.cash'), -1);
|
||||
assert.equal(ev('S.pops.fra.routers'), 3);
|
||||
for (const net of ['cfl', 'ggl'])
|
||||
assert.equal(ev(`S.caches.filter(c=>c.net==='${net}'&&c.site==='b').length`), 2);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a rejected kit purchase never moves caches or partially installs hardware', t => {
|
||||
const { ev, errors } = setup(t);
|
||||
ev("S.caches=[{id:'c1',city:'fra',net:'cfl'},{id:'c2',city:'fra',net:'cfl'}];S.cash=1;compute()");
|
||||
const before = ev('JSON.stringify({p:S.pops.fra,c:S.caches,cash:S.cash})');
|
||||
ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost});ACT.utilityKit({city:'fra',cost:-1})");
|
||||
assert.equal(ev('JSON.stringify({p:S.pops.fra,c:S.caches,cash:S.cash})'), before);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('odd provider totals are balanced across the whole PoP with the fewest moves', t => {
|
||||
const { ev, errors } = setup(t);
|
||||
ev("Object.assign(S.pops.fra,{gen:true,site2:true,routers:2});for(const [net,n] of [['nfx',3],['cfl',1],['ggl',1]])for(let i=0;i<n;i++)S.caches.push({id:net+i,city:'fra',net});compute()");
|
||||
assert.equal(ev("utilityCacheMoves('fra').length"), 2, 'five boxes all in A require two moves');
|
||||
ev("ACT.utilityKit({city:'fra',cost:0})");
|
||||
assert.equal(ev("S.caches.filter(c=>c.site==='b').length"), 2);
|
||||
assert.equal(ev("['nfx','cfl','ggl'].every(net=>Math.abs(S.caches.filter(c=>c.net===net&&c.site==='b').length-S.caches.filter(c=>c.net===net&&c.site!=='b').length)<=1)"), true);
|
||||
assert.equal(ev("utilityCacheMoves('fra').length"), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('cache batch fills missing provider/site pairs, keeps extra boxes and respects eligibility', t => {
|
||||
const { ev, errors } = setup(t);
|
||||
ev("Object.assign(S.pops.fra,{site2:true,routers:2});S.caches=[{id:'keep1',city:'fra',net:'cfl'},{id:'keep2',city:'fra',net:'cfl',site:'a'}];compute();R.demTo={cfl:NET.cfl.cache.min,ggl:NET.ggl.cache.min-1}");
|
||||
const cash = ev('S.cash'), mo = ev('R.cost.caches');
|
||||
assert.equal(ev("utilityCaches('fra').add.length"), 1);
|
||||
ev("ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})");
|
||||
assert.equal(ev('S.cash'), cash, 'cache hardware is free');
|
||||
assert.equal(ev('R.cost.caches'), mo + ev('CACHE_MO'));
|
||||
assert.equal(ev("S.caches.filter(c=>c.net==='cfl'&&c.site==='b').length"), 1);
|
||||
assert.equal(ev("S.caches.filter(c=>c.net==='cfl').length"), 3, 'extra existing A box kept');
|
||||
assert.equal(ev("S.caches.some(c=>c.net==='ggl')"), false);
|
||||
const stable = ev('JSON.stringify(S.caches)');
|
||||
ev("R.demTo={cfl:NET.cfl.cache.min};ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})");
|
||||
assert.equal(ev('JSON.stringify(S.caches)'), stable);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('one-site requests add only A, then a new second site gets exactly its missing boxes', t => {
|
||||
const { ev, errors } = setup(t);
|
||||
ev("R.demTo=Object.fromEntries(NETS.filter(n=>n.cache).map(n=>[n.id,n.cache.min]));ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})");
|
||||
assert.equal(ev('S.caches.length'), 5);
|
||||
assert.equal(ev("S.caches.every(c=>c.site==='a')"), true);
|
||||
ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost});R.demTo=Object.fromEntries(NETS.filter(n=>n.cache).map(n=>[n.id,n.cache.min]));ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})");
|
||||
assert.equal(ev('S.caches.length'), 10);
|
||||
assert.equal(ev("NETS.filter(n=>n.cache).every(n=>['a','b'].every(s=>S.caches.filter(c=>c.net===n.id&&c.site===s).length===1))"), true);
|
||||
ev("save();S=migrate(JSON.parse(slotRaw(UI.slot)));compute()");
|
||||
assert.equal(ev('S.caches.length'), 10);
|
||||
assert.equal(ev("S.caches.filter(c=>c.site==='b').length"), 5);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('cache requests reject stale eligibility and insufficient port capacity atomically', t => {
|
||||
const { ev, errors } = setup(t);
|
||||
ev("S.pops.fra.site2=true;for(let i=0;i<7;i++)S.caches.push({id:'full'+i,city:'fra',net:'nfx'});compute();R.demTo={cfl:NET.cfl.cache.min};window.q=utilityCaches('fra');ACT.utilities()");
|
||||
assert.equal(ev('q.free'), 1);
|
||||
assert.equal(ev('q.add.length'), 2);
|
||||
assert.equal(ev("document.querySelector('[data-act=utilityCaches]').disabled"), true);
|
||||
const before = ev('JSON.stringify(S.caches)');
|
||||
ev("ACT.utilityCaches({city:'fra',quote:q.key})");
|
||||
assert.equal(ev('JSON.stringify(S.caches)'), before);
|
||||
ev("S.pops.fra.routers=2;R.demTo.ggl=NET.ggl.cache.min;ACT.utilityCaches({city:'fra',quote:q.key,modal:true})");
|
||||
assert.equal(ev('JSON.stringify(S.caches)'), before);
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /quote changed/);
|
||||
ev("ACT.utilityCaches({city:'not-a-city',quote:''})");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('balanced caches keep serving when either site fails', t => {
|
||||
const { ev, errors } = setup(t);
|
||||
ev("Object.assign(S.pops.fra,{site2:true,routers:2,rgen:RG_TOP,bb:{d:5000}});S.caches=[{id:'one',city:'fra',net:'ggl'},{id:'two',city:'fra',net:'ggl'}];compute();ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})");
|
||||
for (const site of ['a', 'b']) {
|
||||
ev(`S.inc=[{id:'site-failure',type:'site',ref:'fra',site:'${site}',until:S.day+2}];compute()`);
|
||||
assert.ok(ev('Object.values(R.useCache).reduce((a,b)=>a+b,0)') > 0);
|
||||
assert.equal(ev(`S.caches.filter(c=>(c.site||'a')==='${site}').every(c=>!R.useCache[c.id])`), true);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
159
tests/utilities.test.js
Normal file
159
tests/utilities.test.js
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
function setup(t, opts) {
|
||||
const h = load(opts);
|
||||
t.after(() => h.dom.window.close());
|
||||
h.ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;UI.speed=0;compute()");
|
||||
return h;
|
||||
}
|
||||
|
||||
test('redundancy kit matches normal purchases, including cash, monthly costs and save reload', t => {
|
||||
const a = setup(t), b = setup(t);
|
||||
const quote = JSON.parse(a.ev("JSON.stringify(utilityKit('fra'))"));
|
||||
const cash = a.ev('S.cash'), monthly = a.ev('R.costMo');
|
||||
a.ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})");
|
||||
b.ev("ACT.addGen({city:'fra'});ACT.addSite({city:'fra'});ACT.addRouter({city:'fra'})");
|
||||
for (const expr of ['S.pops.fra', 'R.cost'])
|
||||
assert.deepEqual(JSON.parse(a.ev(`JSON.stringify(${expr})`)), JSON.parse(b.ev(`JSON.stringify(${expr})`)));
|
||||
assert.equal(a.ev('S.cash'), cash - quote.cost);
|
||||
assert.equal(a.ev('S.cash'), b.ev('S.cash'));
|
||||
assert.equal(a.ev('R.costMo'), monthly + quote.mo);
|
||||
const before = a.ev('JSON.stringify(S)');
|
||||
a.ev("ACT.utilityKit({city:'fra',cost:0})");
|
||||
assert.equal(a.ev('JSON.stringify(S)'), before, 'repeat does not buy more hardware');
|
||||
a.ev("save();S=migrate(JSON.parse(slotRaw(UI.slot)));compute()");
|
||||
assert.equal(a.ev('S.pops.fra.gen && S.pops.fra.site2 && S.pops.fra.routers===2'), true);
|
||||
assert.deepEqual(a.errors, []);
|
||||
assert.deepEqual(b.errors, []);
|
||||
});
|
||||
|
||||
test('kit is all-or-nothing, rejects stale quotes and handles missing PoPs', t => {
|
||||
const { ev, errors } = setup(t);
|
||||
ev("window.quote=utilityKit('fra').cost;S.cash=quote-1");
|
||||
const before = ev('JSON.stringify(S.pops.fra)');
|
||||
ev("ACT.utilityKit({city:'fra',cost:quote})");
|
||||
assert.equal(ev('JSON.stringify(S.pops.fra)'), before);
|
||||
assert.equal(ev('S.cash'), ev('quote-1'));
|
||||
ev("S.cash=1e8;ACT.utilityKit({city:'fra',cost:quote+1,modal:true})");
|
||||
assert.equal(ev('JSON.stringify(S.pops.fra)'), before);
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /quote changed/);
|
||||
ev("ACT.utilityKit({city:'not-a-city',cost:0});ACT.utilityKit({city:'ams',cost:0})");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('kit buys only missing components and preserves extra routers and service placement', t => {
|
||||
const { ev, errors } = setup(t);
|
||||
ev("S.pops.fra.routers=4;S.pops.fra.gen=true;S.pops.fra.rgen=3;S.transit.push({id:'test',city:'fra',net:'cog',tier:0,site:'a'});compute()");
|
||||
const cash = ev('S.cash');
|
||||
assert.equal(ev("utilityKit('fra').cost"), ev('SITE2_COST'));
|
||||
ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})");
|
||||
assert.equal(ev('S.cash'), cash - ev('SITE2_COST'));
|
||||
assert.equal(ev('S.pops.fra.routers'), 4);
|
||||
assert.equal(ev('S.pops.fra.rgen'), 3);
|
||||
assert.equal(ev('S.transit[0].site'), 'a');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('bulk peering covers rival IXs, respects policy and is idempotent', t => {
|
||||
const { ev, errors } = setup(t);
|
||||
ev("ACT.buildPop({city:'ams'});ACT.buyIx({city:'fra',tier:0,signed:true});ACT.buyIx({city:'ams',tier:0});ACT.buyIx({city:'ams~3',tier:0});ACT.rs({city:'ams'});compute()");
|
||||
const expected = JSON.parse(ev("JSON.stringify(utilityPeers().flatMap(r=>r.requests.map(id=>id+'@'+r.ix)))"));
|
||||
assert.ok(expected.length > 0);
|
||||
assert.ok(expected.some(k => k.endsWith('@ams~3')));
|
||||
const blocked = JSON.parse(ev("JSON.stringify(utilityPeers().flatMap(r=>r.blocked.map(b=>b.id+'@'+r.ix)))"));
|
||||
assert.ok(blocked.length > 0);
|
||||
const cash = ev('S.cash'), ports = ev('JSON.stringify(S.ixp)'), pnis = ev('JSON.stringify(S.pni)');
|
||||
ev('ACT.utilityPeers()');
|
||||
for (const k of expected) assert.equal(ev(`S.peers[${JSON.stringify(k)}]`), true, k);
|
||||
for (const k of blocked) assert.equal(ev(`!!S.peers[${JSON.stringify(k)}]`), false, k);
|
||||
assert.equal(ev('S.cash'), cash);
|
||||
assert.equal(ev('JSON.stringify(S.ixp)'), ports);
|
||||
assert.equal(ev('JSON.stringify(S.pni)'), pnis);
|
||||
const peers = ev('JSON.stringify(S.peers)');
|
||||
ev('ACT.utilityPeers()');
|
||||
assert.equal(ev('JSON.stringify(S.peers)'), peers);
|
||||
assert.equal(ev('utilityPeers().reduce((n,r)=>n+r.requests.length,0)'), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('bulk peering skips disconnected IXs, route server coverage and existing down sessions', t => {
|
||||
const { ev, errors } = setup(t);
|
||||
assert.equal(ev('utilityPeers().length'), 0);
|
||||
ev("ACT.utilityPeers();ACT.buyIx({city:'fra',tier:0,signed:true});ACT.rs({city:'fra'});S.peers['ggl@fra']=true;compute()");
|
||||
assert.equal(ev("utilityPeers()[0].requests.includes('drz')"), false);
|
||||
assert.equal(ev("utilityPeers()[0].requests.includes('ggl')"), false);
|
||||
ev("ACT.cancelIx({city:'fra',sure:1,ok:1});ACT.utilityPeers()");
|
||||
assert.equal(ev('utilityPeers().length'), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('utilities are available from the Ops sheet in the menu and from PoP Infra in every language', t => {
|
||||
for (const lang of ['en', 'it', 'pt', 'fr', 'es']) {
|
||||
const { ev, dom, errors } = setup(t, lang === 'en' ? {} : { lang });
|
||||
ev('ACT.menu()');
|
||||
dom.window.document.querySelector('#modalCard [data-act="opsOpen"]').click();
|
||||
assert.ok(dom.window.document.querySelector('#modalCard [data-act="utilities"]'), lang);
|
||||
ev("selectCity('fra');ACT.tab({t:'links'})");
|
||||
assert.ok(dom.window.document.querySelector('#panelBody [data-act="utilityKit"]'), lang);
|
||||
ev('ACT.utilities()');
|
||||
assert.equal(dom.window.document.querySelector('#utilityCity').value, 'fra');
|
||||
assert.ok(!dom.window.document.querySelector('#modalCard').textContent.includes('utilities.'), lang);
|
||||
assert.deepEqual(errors, [], lang);
|
||||
}
|
||||
});
|
||||
|
||||
test('join all route servers preserves existing sessions and covers rival and remote IX ports', t => {
|
||||
const { ev, errors } = setup(t);
|
||||
ev("ACT.buyIx({city:'fra',tier:0,signed:true});ACT.rs({city:'fra'});window.fabric=FABS.find(f=>f.cities.includes('fra')&&f.cities.includes('ams')).id;S.links.push({id:'remote',a:'fra',b:'ams',kind:'vxc',prov:fabric,vt:1,km:kmBetween('fra','ams'),sub:false,mo:0,cut:0,day:S.day});ACT.buyIx({city:'ams',tier:0});ACT.buyIx({city:'ams~3',tier:0});compute()");
|
||||
assert.equal(ev("isRemote('ams')"), true);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(utilityRouteServers().sort())')), ['ams', 'ams~3']);
|
||||
const cash = ev('S.cash'), ports = ev('JSON.stringify(S.ixp)'), peers = ev('JSON.stringify(S.peers)');
|
||||
ev('ACT.utilityRouteServers()');
|
||||
assert.equal(ev("S.rs.fra && S.rs.ams && S.rs['ams~3']"), true);
|
||||
assert.equal(ev("ixSessions('ams').has('drz')"), true);
|
||||
assert.equal(ev('S.cash'), cash);
|
||||
assert.equal(ev('JSON.stringify(S.ixp)'), ports);
|
||||
assert.equal(ev('JSON.stringify(S.peers)'), peers);
|
||||
const rs = ev('JSON.stringify(S.rs)');
|
||||
ev('ACT.utilityRouteServers()');
|
||||
assert.equal(ev('JSON.stringify(S.rs)'), rs, 'repeat never toggles a session off');
|
||||
assert.equal(ev('utilityRouteServers().length'), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('route-server batch leaves peering policy and player-owned exchanges alone', t => {
|
||||
const { ev, errors } = setup(t);
|
||||
ev('ACT.utilityRouteServers()');
|
||||
assert.equal(ev('Object.keys(S.rs).length'), 0, 'does not join an IX without a port');
|
||||
ev("ACT.buyIx({city:'fra',tier:0,signed:true});ACT.peerPol({p:'closed'});ACT.utilityRouteServers()");
|
||||
assert.equal(ev('ppol()'), 'closed');
|
||||
assert.equal(ev('S.rs.fra'), true);
|
||||
assert.equal(ev("ixSessions('fra').has('drz')"), false, 'does not bypass closed policy');
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /Off while your peering policy/);
|
||||
ev("S.myIx.fra={members:[],fab:0};S.rs.fra=false;ACT.utilityRouteServers()");
|
||||
assert.equal(ev('S.rs.fra'), false, 'owned exchange has no join-route-server control');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#192 the Infra tab shows the kit as one line, without repeating its rows', t => {
|
||||
for (const w of [1280, 360]) {
|
||||
const { ev, dom, errors } = setup(t);
|
||||
ev(`window.innerWidth=${w}`);
|
||||
ev("S.caches=[{id:'c1',city:'fra',net:'cfl'},{id:'c2',city:'fra',net:'cfl'}];compute();selectCity('fra');ACT.tab({t:'links'})");
|
||||
const body = dom.window.document.getElementById('panelBody');
|
||||
const txt = body.textContent;
|
||||
assert.match(txt, /PoP redundancy kit · One-off: /);
|
||||
assert.doesNotMatch(txt, /Second site(None|Installed)/, 'no second copy of the second-site row');
|
||||
assert.doesNotMatch(txt, /At least two routers/, 'no second copy of the routers row');
|
||||
assert.doesNotMatch(txt, /Request missing caches/, 'caches are in the Peering tab and Utilities');
|
||||
assert.equal(body.querySelectorAll('section h3').length, [...body.querySelectorAll('section h3')].filter(h => h.textContent !== 'PoP redundancy kit').length);
|
||||
assert.equal(txt.split('Backup generator').length - 1, 1, 'the generator shows once, in Power');
|
||||
assert.ok(body.querySelector('[data-act="utilityKit"]'), 'the kit is one tap away');
|
||||
body.querySelector('[data-act="utilities"]').click();
|
||||
assert.match(dom.window.document.getElementById('modalCard').textContent, /At least two routers/, 'the full kit is in Utilities');
|
||||
assert.equal(dom.window.document.querySelector('#utilityCity').value, 'fra');
|
||||
assert.deepEqual(errors, [], `${w}px`);
|
||||
}
|
||||
});
|
||||
89
tests/weekly-architect.test.js
Normal file
89
tests/weekly-architect.test.js
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
// The weekly Architect run: generated every Sunday (scripts/weekly-architect.js), checked by the game field by field,
|
||||
// and played like the handmade runs.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
const { game } = require('../scripts/weekly-puzzle');
|
||||
const AW = require('../scripts/weekly-architect');
|
||||
|
||||
const DIR = path.join(__dirname, '..', 'site', 'architect', 'weekly');
|
||||
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'sot-arwk-'));
|
||||
|
||||
test('the generator makes the same run for the same week, and its reference earns three stars', () => {
|
||||
const g = game(), a = AW.generate(g, '2026-W50', tmp()), b = AW.generate(g, '2026-W50', tmp());
|
||||
assert.deepEqual(a, b, 'deterministic');
|
||||
assert.ok(a.briefs.length >= 6 && a.briefs.length <= 7);
|
||||
assert.ok(a.ref.steps.every((st) => st.length >= 1), 'every brief asks for a change: a tube, a bigger tube or a move');
|
||||
assert.ok(a.briefs.some((x) => x.gold), 'something is mission-critical');
|
||||
assert.ok(a.budget >= a.ref.spend && a.budget <= a.ref.spend * 1.1 + 10000, 'the budget sits just above the reference');
|
||||
assert.equal(AW.verify(g, a, '2026-W50').ok, true);
|
||||
});
|
||||
|
||||
test('a grow brief makes the reference make room: a bigger tube or a second one', () => {
|
||||
const g = game(), d = tmp(), runs = ['2026-W47', '2026-W49', '2026-W53'].map((k) => AW.generate(g, k, d));
|
||||
const grows = runs.flatMap((j) => j.briefs.map((b, i) => [j, b, i]).filter(([, b]) => b.dem && !b.add));
|
||||
assert.ok(grows.length >= 1, 'some weeks grow a site');
|
||||
for (const [j, b, i] of grows) {
|
||||
const [c, gb] = Object.entries(b.dem)[0];
|
||||
assert.ok(gb > 100 || j.briefs.slice(0, i).some((x) => x.dem && x.dem[c] && x.dem[c] < gb), 'the site really grows');
|
||||
assert.ok(j.ref.steps[i].length >= 1, 'and that brief takes a change');
|
||||
}
|
||||
const { ev } = load();
|
||||
const [j, b] = grows[0];
|
||||
ev(`UI.arWk={key:'${j.key}',def:arWkValid(${JSON.stringify(j)},'${j.key}'),at:Date.now()}`);
|
||||
const c = Object.keys(b.dem)[0];
|
||||
assert.ok(ev(`UI.arWk.def.briefs.some(x=>x.t.includes(CITY['${c}'].name+' grows to'))`), 'the brief says so');
|
||||
});
|
||||
|
||||
test('every published week is accepted and its reference still earns three stars', () => {
|
||||
const keys = AW.list(DIR);
|
||||
assert.ok(keys.length >= 3);
|
||||
assert.deepEqual(AW.check(game(), DIR, 0), []);
|
||||
});
|
||||
|
||||
test('the game refuses a file that does not add up', () => {
|
||||
const { ev } = load();
|
||||
const j = JSON.parse(fs.readFileSync(path.join(DIR, AW.list(DIR)[0] + '.json'), 'utf8')), k = j.key;
|
||||
const ok = (o) => ev(`!!arWkValid(${JSON.stringify(o)},'${k}')`);
|
||||
assert.equal(ok(j), true);
|
||||
const bad = (f) => { const o = JSON.parse(JSON.stringify(j)); f(o); return ok(o); };
|
||||
assert.equal(ev(`!!arWkValid(${JSON.stringify(j)},'2030-W01')`), false, 'under another week');
|
||||
assert.equal(bad((o) => { o.extra = 1; }), false, 'an unknown field');
|
||||
assert.equal(bad((o) => { o.hq = 'atlantis'; }), false, 'an unknown HQ');
|
||||
assert.equal(bad((o) => { o.name.l = 'common.play'; }), false, 'a label it may not name');
|
||||
assert.equal(bad((o) => { o.briefs[0] = { tubes: 1 }; }), false, 'a brief that asks for nothing');
|
||||
assert.equal(bad((o) => { o.briefs[1].gold = [o.hq]; }), false, 'HQ made mission-critical');
|
||||
assert.equal(bad((o) => { o.briefs[1].gold = ['tok']; }), false, 'a site that is not in the run yet');
|
||||
assert.equal(bad((o) => { o.briefs.push({ lat: [o.hq, o.briefs[0].add[0], 0.5], tubes: 1 }); }), false, 'a latency cap below 1 ms');
|
||||
assert.equal(bad((o) => { o.budget = 1e9; }), false, 'a silly budget');
|
||||
});
|
||||
|
||||
test('this week\'s run shows in Puzzles, plays like a handmade one and keeps its own stars', () => {
|
||||
const { ev, errors, dom } = load();
|
||||
const key = ev('pzWeekKey(new Date())'), j = AW.generate(game(), key, tmp());
|
||||
ev(`UI.arWk={key:'${key}',def:arWkValid(${JSON.stringify(j)},'${key}'),at:Date.now()}`);
|
||||
ev('ACT.puzzleMenu()');
|
||||
const row = dom.window.document.getElementById('arWk');
|
||||
assert.ok(row && row.querySelector('[data-act=pzArStart]'), 'a row with a Play button');
|
||||
assert.match(row.textContent, /This week’s Architect run/);
|
||||
row.querySelector('[data-act=pzArStart]').click();
|
||||
assert.equal(ev('S.ar.id'), 'wk-' + key);
|
||||
assert.match(ev('arBrief().t'), /signs up: connect it\./, 'the brief is written from what it asks');
|
||||
assert.equal(ev(`arHide('${j.briefs[1].add[0]}')`), true, 'the next brief\'s cities stay hidden');
|
||||
// The reference, played through: three stars, stored under the week, and no handmade run offered as "next".
|
||||
j.ref.steps.forEach((st, i) => {
|
||||
for (const s of st) AW.step(ev, s);
|
||||
ev('arShowStart();arShowSkip()');
|
||||
assert.ok(ev('S.ar.passed===pzSig()'), `brief ${i + 1} passes`);
|
||||
ev('ACT.pzArNext()');
|
||||
});
|
||||
assert.equal(ev(`arLoad().runs['wk-${key}'].st`), 3);
|
||||
assert.equal(ev("document.querySelector('#modalCard [data-act=pzArStart]')"), null, 'no "next run" after a weekly one');
|
||||
// A regenerated week (rev 2) starts its stars again.
|
||||
ev(`UI.arWk.def.rev=2;ACT.puzzleMenu()`);
|
||||
assert.match(dom.window.document.getElementById('arWk').textContent, /⬜⬜⬜/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
297
tests/weekly-puzzle.test.js
Normal file
297
tests/weekly-puzzle.test.js
Normal file
|
|
@ -0,0 +1,297 @@
|
|||
// The published weekly puzzle: Sunday 06:00 Berlin weeks, the generator (scripts/weekly-puzzle.js), its --check,
|
||||
// and the game's fetch: only when Puzzles opens, validated strictly, with the seeded weekly as the fallback.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
const G = require('../scripts/weekly-puzzle');
|
||||
|
||||
const DIR = path.join(__dirname, '..', 'site', 'puzzles', 'weekly');
|
||||
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-weekly-'));
|
||||
const committed = () => G.list(DIR).map((k) => JSON.parse(fs.readFileSync(path.join(DIR, k + '.json'), 'utf8')));
|
||||
const tick = () => new Promise((r) => setTimeout(r, 30));
|
||||
|
||||
test('weeks start Sunday 06:00 Berlin, in winter and in summer, and keys run across New Year', () => {
|
||||
const { ev, errors } = load();
|
||||
const key = (iso) => ev(`pzWeekKey(new Date('${iso}'))`), start = (k) => ev(`new Date(pzWeekStart('${k}')).toISOString()`);
|
||||
// Winter (CET, UTC+1): 06:00 Berlin is 05:00 UTC.
|
||||
assert.equal(key('2026-11-01T04:59:59Z'), '2026-W44');
|
||||
assert.equal(key('2026-11-01T05:00:00Z'), '2026-W45', 'the week starting Sunday 1 Nov is named after its Monday');
|
||||
assert.equal(key('2026-11-07T23:00:00Z'), '2026-W45', 'Saturday night is still the same week');
|
||||
assert.equal(start('2026-W45'), '2026-11-01T05:00:00.000Z');
|
||||
// Summer (CEST, UTC+2): 06:00 Berlin is 04:00 UTC.
|
||||
assert.equal(key('2026-07-05T03:59:00Z'), '2026-W27');
|
||||
assert.equal(key('2026-07-05T04:00:00Z'), '2026-W28');
|
||||
// The weekends the clocks change: the change is at 01:00 UTC that same Sunday, before the week starts.
|
||||
assert.equal(start('2026-W14'), '2026-03-29T04:00:00.000Z', 'spring forward: first CEST Sunday');
|
||||
assert.equal(start('2026-W13'), '2026-03-22T05:00:00.000Z');
|
||||
assert.equal(start('2026-W44'), '2026-10-25T05:00:00.000Z', 'fall back: first CET Sunday');
|
||||
assert.equal(start('2026-W43'), '2026-10-18T04:00:00.000Z');
|
||||
assert.equal(key('2026-03-29T03:59:00Z'), '2026-W13');
|
||||
assert.equal(key('2026-03-29T04:00:00Z'), '2026-W14');
|
||||
assert.equal(key('2026-10-25T04:59:00Z'), '2026-W43');
|
||||
assert.equal(key('2026-10-25T05:00:00Z'), '2026-W44');
|
||||
// New Year: 2026 has 53 ISO weeks, 2027 has 52.
|
||||
assert.equal(key('2026-12-27T05:00:00Z'), '2026-W53');
|
||||
assert.equal(key('2027-01-03T04:59:00Z'), '2026-W53');
|
||||
assert.equal(key('2027-01-03T05:00:00Z'), '2027-W01');
|
||||
assert.equal(key('2027-12-26T05:00:00Z'), '2027-W52');
|
||||
assert.equal(key('2028-01-02T05:00:00Z'), '2028-W01');
|
||||
assert.equal(ev("pzKeyAdd('2026-W53',1)"), '2027-W01');
|
||||
assert.equal(ev("pzPrevKey('2027-W01')"), '2026-W53');
|
||||
assert.equal(ev("pzPrevKey('2028-W01')"), '2027-W52');
|
||||
assert.equal(ev("pzWeekStart('2027-W53')"), null, '2027 has no week 53');
|
||||
assert.equal(ev("pzWeekStart('2026-W00')"), null);
|
||||
assert.equal(ev("pzWeekStart('nope')"), null);
|
||||
// Every week of ten years: 7 days apart (give or take the DST hour), keys round-trip, never two Sundays the same key.
|
||||
let k = '2026-W01', seen = new Set();
|
||||
for (let i = 0; i < 522; i++) {
|
||||
const t = ev(`pzWeekStart('${k}')`), n = ev(`pzKeyAdd('${k}',1)`), tn = ev(`pzWeekStart('${n}')`);
|
||||
assert.equal(new Date(t).getUTCDay(), 0, `${k} starts on a Sunday`);
|
||||
assert.ok([7 * 864e5, 7 * 864e5 - 3600e3, 7 * 864e5 + 3600e3].includes(tn - t), `${k} → ${n}`);
|
||||
assert.equal(ev(`pzWeekKey(${t})`), k);
|
||||
assert.equal(ev(`pzWeekKey(${t - 1})`), ev(`pzPrevKey('${k}')`));
|
||||
assert.ok(!seen.has(k)); seen.add(k); k = n;
|
||||
}
|
||||
// The countdown.
|
||||
assert.equal(ev("pzWkNext(Date.parse('2026-10-29T14:00:00Z'))"), 'Next weekly puzzle in 2 d 15 h');
|
||||
assert.equal(ev("pzWkNext(Date.parse('2026-11-01T03:20:00Z'))"), 'Next weekly puzzle in 1 h 40 min');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// Weeks already out are not compared with a fresh run: a later release may change prices, and a published week stays as
|
||||
// it was (--check still makes sure the weeks not over yet can be solved).
|
||||
test('generator: deterministic for a week', () => {
|
||||
const g = G.game(), a = tmp(), b = tmp();
|
||||
const first = G.list(DIR).slice(-3)[0];
|
||||
const keys = Math.min(3, G.list(DIR).length);
|
||||
for (const d of [a, b]) for (let i = 0; i < keys; i++) G.writeWeek(d, G.generate(g, g.ev(`pzKeyAdd('${first}',${i})`), d));
|
||||
for (const k of G.list(a)) {
|
||||
assert.equal(fs.readFileSync(path.join(a, k + '.json'), 'utf8'), fs.readFileSync(path.join(b, k + '.json'), 'utf8'), `${k} twice the same`);
|
||||
}
|
||||
assert.ok(G.list(DIR).length >= 3, 'the release ships with weeklies in place');
|
||||
});
|
||||
|
||||
test('generator: a quarter of weeks, all verified, varied, small and in the schema', () => {
|
||||
const g = G.game(), d = tmp();
|
||||
let k = '2027-W10';
|
||||
const out = [];
|
||||
for (let i = 0; i < 12; i++, k = g.ev(`pzKeyAdd('${k}',1)`)) { const j = G.generate(g, k, d); G.writeWeek(d, j); out.push(j); }
|
||||
assert.deepEqual(G.check(g, d, 0), [], 'every week verifies: both references earn their stars in the game');
|
||||
for (let i = 1; i < out.length; i++) {
|
||||
assert.notEqual(out[i].theme, out[i - 1].theme, `${out[i].key}: not last week's theme`);
|
||||
for (const c of out[i].cities) assert.ok(!out[i - 1].cities.includes(c), `${out[i].key}: ${c} was a city last week too`);
|
||||
}
|
||||
assert.ok(new Set(out.map((j) => j.theme)).size >= 5, 'most themes come round in a quarter');
|
||||
for (const j of out) {
|
||||
assert.ok(j.cities.length >= 3 && j.cities.length <= 6);
|
||||
assert.ok(j.ref.one <= j.ref.three && j.ref.three <= j.budget && j.budget <= j.ref.three * 1.06 + 10000, `${j.key}: budget ${j.budget} just above the N-1 build ${j.ref.three}`);
|
||||
assert.ok(JSON.stringify(j).length < 900, 'small file');
|
||||
assert.ok(j.dem.length >= 2 && j.src.length === 1 && j.dem.every((f) => f.g > 0), `${j.key}: it carries traffic`);
|
||||
assert.deepEqual(Object.keys(j), ['v', 'key', 'theme', 'cities', 'src', 'dem', 'via', 'avoid', 'budget', 'twist', 'name', 'joke', 'ref']);
|
||||
}
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(d, 'index.json'), 'utf8')).weeks, out.map((j) => j.key));
|
||||
});
|
||||
|
||||
test('--check passes on the committed files and rejects tampered ones', () => {
|
||||
const g = G.game();
|
||||
// Weeks still to come are re-solved; past ones are checked the way the game reads them. check() only reports;
|
||||
// refresh() (the first half of --check) is what fixes.
|
||||
assert.deepEqual(G.check(g, DIR), [], 'committed weeklies verify');
|
||||
const bad = (edit, why) => {
|
||||
const d = tmp();
|
||||
for (const k of G.list(DIR).slice(-3)) fs.copyFileSync(path.join(DIR, k + '.json'), path.join(d, k + '.json'));
|
||||
G.writeIndex(d);
|
||||
const k = G.list(d)[0], f = path.join(d, k + '.json'), j = JSON.parse(fs.readFileSync(f, 'utf8'));
|
||||
const r = edit(j, d, k); fs.writeFileSync(f, typeof r === 'string' ? r : JSON.stringify(j));
|
||||
assert.notDeepEqual(G.check(g, d, 0), [], why);
|
||||
};
|
||||
bad((j) => { j.budget = Math.floor(j.ref.three * 0.8 / 10000) * 10000; j.ref.three = j.budget - 1; }, 'a budget nobody can earn three stars under');
|
||||
bad((j) => { j.cities[0] = 'xxx'; }, 'an unknown city');
|
||||
bad((j) => { j.name.l = 'puzzles.hello_world'; }, 'a label that is not a weekly name');
|
||||
bad((j) => { j.joke.p = { hub: 'fra' }; }, 'parameters the label does not take');
|
||||
bad((j) => { j.extra = '<img src=x onerror=alert(1)>'; }, 'an unknown field');
|
||||
bad((j) => { j.key = '2030-W01'; }, 'a file under another week\'s name');
|
||||
bad((j) => { j.dem.push({ t: 'l2', a: j.cities[0], b: j.cities[1], g: 10, ms: 1 }); }, 'an impossible latency target');
|
||||
bad((j) => { j.dem[0].g = 5000; }, 'more traffic than a puzzle carries');
|
||||
bad(() => '{nope', 'not JSON');
|
||||
bad((j, d) => { fs.writeFileSync(path.join(d, 'index.json'), '{"v":1,"weeks":[]}'); }, 'an index that misses weeks');
|
||||
});
|
||||
|
||||
test('--check regenerates a published week when new prices break its budget, and only then', () => {
|
||||
const g = G.game(), d = tmp();
|
||||
for (const k of G.list(DIR)) fs.copyFileSync(path.join(DIR, k + '.json'), path.join(d, k + '.json'));
|
||||
G.writeIndex(d);
|
||||
const read = (k) => JSON.parse(fs.readFileSync(path.join(d, k + '.json'), 'utf8')), [k0, k1] = G.list(d).slice(-2);
|
||||
assert.deepEqual(G.refresh(g, d, 0), { fixed: [], bad: [] }, 'the committed weeks still verify: nothing changes');
|
||||
// Prices went up: the old budget no longer buys the N-1 build. The same puzzle comes back with a budget that does.
|
||||
const old = read(k0), j = read(k0); j.budget = Math.floor(j.ref.three * 0.8 / 10000) * 10000; j.ref.three = j.budget - 1;
|
||||
fs.writeFileSync(path.join(d, k0 + '.json'), JSON.stringify(j));
|
||||
const r = G.refresh(g, d, 0);
|
||||
assert.deepEqual(r.bad, []);
|
||||
assert.equal(r.fixed.length, 1, r.fixed.join('; '));
|
||||
const n = read(k0);
|
||||
assert.equal(n.rev, 2, 'a new revision');
|
||||
assert.deepEqual([n.theme, n.cities, n.via, n.avoid, n.twist, n.name, n.joke], [old.theme, old.cities, old.via, old.avoid, old.twist, old.name, old.joke], 'the same puzzle');
|
||||
assert.ok(n.budget >= n.ref.three && n.ref.three > j.budget);
|
||||
assert.deepEqual(G.check(g, d, 0), [], 'and it verifies');
|
||||
assert.deepEqual(G.refresh(g, d, 0), { fixed: [], bad: [] }, 'deterministic and settled: a second run changes nothing');
|
||||
// A week the game rejects (a city that is gone) gets a fresh puzzle under the same key.
|
||||
const b = read(k1); b.cities[0] = 'xxx'; fs.writeFileSync(path.join(d, k1 + '.json'), JSON.stringify(b));
|
||||
assert.equal(G.refresh(g, d, 0).fixed.length, 1);
|
||||
assert.equal(read(k1).key, k1);
|
||||
assert.equal(read(k1).rev, 2);
|
||||
assert.deepEqual(G.check(g, d, 0), []);
|
||||
// Weeks that are over cannot be played again: their stars stay, so a broken budget there is left alone.
|
||||
const e = read(k0); e.budget = 50000; fs.writeFileSync(path.join(d, k0 + '.json'), JSON.stringify(e));
|
||||
assert.deepEqual(G.refresh(g, d, 8.64e15), { fixed: [], bad: [] });
|
||||
});
|
||||
|
||||
test('stars belong to the revision of the week they were earned on', () => {
|
||||
const { ev, errors } = load();
|
||||
const j = committed()[0], k = j.key, ok = (o) => ev(`!!pzWkValid(${JSON.stringify(o)},'${k}')`);
|
||||
assert.equal(ev(`pzWkValid(${JSON.stringify(j)},'${k}').rev`), 1, 'a first edition is rev 1');
|
||||
assert.ok(ok({ ...j, rev: 2 }));
|
||||
for (const rev of [1, 0, '2', 2.5, 1000]) assert.equal(ok({ ...j, rev }), false, `rev ${rev}`);
|
||||
ev(`localStorage.setItem('sot-puzzles',JSON.stringify({wk:{'${k}':{st:3,sp:1},'2026-W01':{st:2,sp:5}}}))`);
|
||||
assert.equal(ev(`pzWkRec(pzLoad(),pzWkValid(${JSON.stringify(j)},'${k}')).st`), 3, 'same week, same revision: the stars stand');
|
||||
const d2 = `pzWkValid(${JSON.stringify({ ...j, rev: 2 })},'${k}')`;
|
||||
assert.equal(ev(`pzWkRec(pzLoad(),${d2})`), null, 'regenerated: that week starts again');
|
||||
ev(`pzBegin(${d2});pzRecord({stars:1,spend:9})`);
|
||||
const p = JSON.parse(ev("localStorage.getItem('sot-puzzles')"));
|
||||
assert.deepEqual(p.wk[k], { st: 1, sp: 9, rv: 2 }, 'a lower score on the new revision replaces the old one');
|
||||
assert.deepEqual(p.wk['2026-W01'], { st: 2, sp: 5 }, 'other weeks keep theirs');
|
||||
assert.equal(ev(`pzWkRec(pzLoad(),${d2}).st`), 1);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the page never asks for a weekly puzzle on load, only when Puzzles opens', async () => {
|
||||
const { ev, errors } = load();
|
||||
ev("window.__f=[];window.fetch=(u,o)=>{__f.push(String(u));return Promise.resolve({ok:false,json:()=>Promise.reject()})}");
|
||||
ev("showTitle();for(let i=0;i<5;i++)frame(performance.now()+i*1000);renderAll()");
|
||||
assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 0, 'nothing on the title screen');
|
||||
assert.equal(ev("UI.pzWk===undefined"), true);
|
||||
ev("ACT.start({});for(let i=0;i<3;i++)dayTick();renderAll()");
|
||||
assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 0, 'nothing while playing');
|
||||
ev('ACT.puzzleMenu({})');
|
||||
const key = ev('pzWeekKey(new Date())');
|
||||
assert.deepEqual(ev("JSON.stringify(__f.filter(u=>/puzzles/.test(u)))"), JSON.stringify([`puzzles/weekly/${key}.json`]), 'one relative, same-origin request');
|
||||
ev('closeModal();ACT.puzzleMenu({})');
|
||||
assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 1, 'once is enough while it is loading');
|
||||
await tick();
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the published puzzle is played when it is good, the seeded one when it is missing, offline or bad', async () => {
|
||||
const src = committed()[1], { ev, dom, errors } = load();
|
||||
const key = ev('pzWeekKey(new Date())'), good = { ...src, key };
|
||||
const serve = (how) => { ev(`UI.pzWk=null;window.fetch=()=>${how}`); ev('ACT.puzzleMenu({})'); };
|
||||
const seeded = JSON.parse(ev('JSON.stringify(pzWeekly())'));
|
||||
for (const [how, why] of [
|
||||
["Promise.resolve({ok:false,status:404,json:()=>Promise.reject()})", 'missing'],
|
||||
["Promise.reject(new TypeError('offline'))", 'offline'],
|
||||
["Promise.resolve({ok:true,json:()=>Promise.reject(new SyntaxError('x'))})", 'not JSON'],
|
||||
[`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, cities: ['fra', 'nope', 'ams'] })})})`, 'an unknown city'],
|
||||
[`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, key: '2020-W01' })})})`, 'another week'],
|
||||
]) {
|
||||
serve(how);
|
||||
await tick();
|
||||
assert.equal(ev('UI.pzWk.st'), 'fb', why);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(pzWkDef().cities)')), seeded.cities, `${why}: the seeded weekly stands in`);
|
||||
assert.match(ev("document.getElementById('pzWk').textContent"), new RegExp(`Weekly puzzle ${key}`));
|
||||
assert.equal(ev("document.querySelector('#pzWk [data-act=pzWeekly]').disabled"), false);
|
||||
}
|
||||
// While it loads, the button waits a moment.
|
||||
ev("UI.pzWk=null;window.fetch=()=>new Promise(()=>{})");
|
||||
ev('ACT.puzzleMenu({})');
|
||||
assert.match(ev("document.getElementById('pzWk').textContent"), /Loading this week/);
|
||||
assert.equal(ev("document.querySelector('#pzWk [data-act=pzWeekly]').disabled"), true);
|
||||
// The good one.
|
||||
serve(`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify(good)})})`);
|
||||
await tick();
|
||||
assert.equal(ev('UI.pzWk.st'), 'ok');
|
||||
const row = ev("document.getElementById('pzWk').textContent");
|
||||
assert.ok(row.includes(ev('pzName(pzWkDef())')), 'its pun name');
|
||||
assert.ok(row.includes(ev('pzTxt(pzWkDef().wj)')), 'its joke');
|
||||
assert.match(row, /New this Sunday!/);
|
||||
assert.match(row, /Next weekly puzzle in \d+ (d \d+ h|h \d+ min)/);
|
||||
ev("document.querySelector('#pzWk [data-act=pzWeekly]').click()");
|
||||
assert.equal(ev('S.pz.key'), key);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.pz.cities)')), good.cities);
|
||||
assert.equal(ev('S.pz.budget'), good.budget);
|
||||
assert.match(ev("document.getElementById('pzBox').textContent"), new RegExp(ev('pzTxt(S.pz.wj)').replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
|
||||
// Solve it with three stars: the share line and the streak use the published key.
|
||||
// The generator's sized 3-star reference, played into this puzzle (links, routers, routes).
|
||||
const SV = require('../scripts/lib/puzzle-solver');SV.install(ev);
|
||||
const def = JSON.parse(ev('JSON.stringify(pzWkDef())')), sol = G.sized({ ev }, G.world(ev), G.shape(def), def).three.b;
|
||||
ev('pzBegin(pzWkDef())');
|
||||
SV.judge(ev, sol.links);
|
||||
ev(`pzsApplyRt(${JSON.stringify(sol.rt)});pzAfter()`);
|
||||
assert.equal(ev('pzEval().stars'), 3);
|
||||
assert.match(ev('pzShareText(pzEval())'), new RegExp(`^Series of Tubes puzzle ${key} ⭐⭐⭐ \\$[\\d.]+[kM] · seriesoftub\\.es$`));
|
||||
const p = JSON.parse(ev("localStorage.getItem('sot-puzzles')"));
|
||||
assert.equal(p.wk[key].st, 3);
|
||||
assert.equal(p.streak.last, key);
|
||||
ev('ACT.pzLeave({})');
|
||||
assert.doesNotMatch(ev("document.querySelector('.door[data-door=puzzle]').textContent"), /New this Sunday/, 'played: no badge');
|
||||
void dom;
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the file is checked field by field', () => {
|
||||
const { ev, errors } = load();
|
||||
const j = committed()[0], k = j.key, ok = (o) => ev(`!!pzWkValid(${JSON.stringify(o)},'${k}')`);
|
||||
assert.ok(ok(j));
|
||||
const no = (edit, why) => { const o = JSON.parse(JSON.stringify(j)); edit(o); assert.equal(ok(o), false, why); };
|
||||
no((o) => { o.v = 3; }, 'a newer schema');
|
||||
no((o) => { o.v = 1; }, 'an old file without traffic');
|
||||
no((o) => { o.dem = []; }, 'no traffic');
|
||||
no((o) => { o.dem = [{ t: 'warp', a: o.cities[0], g: 1 }]; }, 'an unknown kind of flow');
|
||||
no((o) => { o.dem = [{ ...o.dem[0], g: 1.5 }, ...o.dem.slice(1)]; }, 'fractional gigabits');
|
||||
no((o) => { o.src = []; }, 'eyeballs with nowhere to pull from');
|
||||
no((o) => { o.cities = o.cities.slice(0, -1); }, 'cities that do not match the traffic');
|
||||
no((o) => { o.theme = 'constructor'; }, 'an unknown theme');
|
||||
no((o) => { o.cities = ['fra']; }, 'too few cities');
|
||||
no((o) => { o.cities = [...o.cities, o.cities[0]]; }, 'a city twice');
|
||||
no((o) => { o.via = [o.cities[0]]; }, 'a goal city as a stepping stone');
|
||||
no((o) => { o.cities[0] = 'pek'; }, 'a city that needs a licence');
|
||||
no((o) => { o.budget = '240000'; }, 'a budget as text');
|
||||
no((o) => { o.budget = 1e9; }, 'a silly budget');
|
||||
no((o) => { o.twist = { ring: 'yes' }; }, 'a twist that is not true');
|
||||
no((o) => { o.twist = { avoidAll: true }; }, 'an unknown twist');
|
||||
no((o) => { o.name = { l: 'puzzles_weekly.name_tour_de_reg', p: { reg: 'XX' } }; }, 'an unknown region');
|
||||
no((o) => { o.name = { l: 'puzzles_weekly.name_race_to_b', p: { b: '<b>' } }; }, 'markup as a city');
|
||||
no((o) => { o.joke = 'Ha ha'; }, 'raw English');
|
||||
no((o) => { o.__proto__ = { budget: 1 }; o.extra = 1; }, 'extra fields');
|
||||
assert.equal(ev(`pzWkValid(null,'${k}')`), null);
|
||||
assert.equal(ev(`pzWkValid([],'${k}')`), null);
|
||||
// Every label a theme may use exists in English, and every file names its text in the player's language.
|
||||
assert.ok(ev("Object.values(PZ_WK_THEMES).every(T=>[T.t,...T.names,...T.jokes].every(l=>typeof EN[l]==='string'))"));
|
||||
for (const f of committed()) {
|
||||
const d = ev(`JSON.stringify(pzWkValid(${JSON.stringify(f)},'${f.key}'))`);
|
||||
assert.ok(d, f.key);
|
||||
assert.doesNotMatch(ev(`(d=>pzTxt(d.wn)+' '+pzTxt(d.wj))(${d})`), /\{|puzzles_weekly\./, `${f.key}: filled in`);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('weekly puzzle in every language and on a 360 px phone', async () => {
|
||||
const f = committed()[0];
|
||||
for (const lang of ['de', 'es', 'fr', 'it', 'pt']) {
|
||||
const { ev, errors } = load({ lang });
|
||||
const key = ev('pzWeekKey(new Date())');
|
||||
ev(`window.fetch=()=>Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...f, key })})})`);
|
||||
ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));showTitle()");
|
||||
ev('ACT.puzzleMenu({})');
|
||||
await tick();
|
||||
const row = ev("document.getElementById('pzWk').textContent");
|
||||
assert.doesNotMatch(row, /puzzles(_weekly)?\.|\{/, `${lang}: no raw labels or placeholders`);
|
||||
assert.notEqual(ev('pzName(pzWkDef())'), ev("EN[pzWkDef().wn.l]"), `${lang}: translated name`);
|
||||
ev("document.querySelector('#pzWk [data-act=pzWeekly]').click()");
|
||||
assert.equal(ev("document.getElementById('pzBox').hidden"), false);
|
||||
assert.doesNotMatch(ev("document.getElementById('pzBox').textContent"), /puzzles(_weekly)?\./);
|
||||
assert.deepEqual(errors, [], lang);
|
||||
}
|
||||
});
|
||||
208
tests/weekly-scenario.test.js
Normal file
208
tests/weekly-scenario.test.js
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
// The published weekly scenario: the generator (scripts/weekly-scenario.js) and its reference player, --check, and the
|
||||
// game's side: fetched only when the Scenarios list opens, validated strictly, the in-browser weekly as the fallback,
|
||||
// a goal type and progress card for each kind of week, the win, the streak and the share line.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
const G = require('../scripts/weekly-scenario');
|
||||
|
||||
const DIR = path.join(__dirname, '..', 'site', 'scenarios', 'weekly');
|
||||
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-wkscn-'));
|
||||
const committed = () => G.list(DIR).map((k) => JSON.parse(fs.readFileSync(path.join(DIR, k + '.json'), 'utf8')));
|
||||
const tick = () => new Promise((r) => setTimeout(r, 30));
|
||||
const serveFile = (ev, j) => ev(`UI.wsWk=null;window.fetch=()=>Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify(j)})})`);
|
||||
// One file per goal type, from the committed ones where a week has it: enough to check every card.
|
||||
const GOALS = {
|
||||
served: { theme: 'budget', goal: { t: 'served', p: { g: 200 } }, desc: { l: 'wkscn.desc_city_on_a_shoestring', p: { city: 'fra' } } },
|
||||
reach: { theme: 'spat', rules: { spat: true }, goal: { t: 'reach', p: { r: 99, g: 150 } }, desc: { l: 'wkscn.desc_two_giants_de_peered_over', p: { city: 'fra' } } },
|
||||
path: { theme: 'cable', rules: { banPairs: ['grace:nyc-lon'] }, goal: { t: 'path', p: { a: 'fra', b: 'nyc', g: 400, n: 30 } }, desc: { l: 'wkscn.desc_cab_is_cut_for_the', p: { cab: 'grace', a: 'fra', b: 'nyc' } } },
|
||||
ix: { theme: 'region', goal: { t: 'ix', p: { reg: 'EU', n: 8 } }, desc: { l: 'wkscn.desc_every_exchange_in_reg_wants', p: { reg: 'EU', city: 'fra' } } },
|
||||
pops: { theme: 'island', goal: { t: 'pops', p: { cs: ['ams', 'par'] } }, desc: { l: 'wkscn.desc_city_is_surrounded_by_water', p: { city: 'fra' } } },
|
||||
event: { theme: 'event', goal: { t: 'event', p: { city: 'fra', g: 400, day: 120, dur: 3 } }, desc: { l: 'wkscn.desc_a_g_event_comes_to', p: { g: 400, city: 'fra', day: 120 } } },
|
||||
floods: { theme: 'flood', rules: { ddos: true }, goal: { t: 'floods', p: { n: 20, big: 2 } }, desc: { l: 'wkscn.desc_booters_picked_city_for_their', p: { city: 'fra' } } },
|
||||
lat: { theme: 'latency', goal: { t: 'lat', p: { a: 'fra', b: 'nyc', ms: 40, n: 30 } }, desc: { l: 'wkscn.desc_a_trading_firm_needs_a', p: { a: 'fra', b: 'nyc', ms: 40 } } },
|
||||
};
|
||||
const NAME = { budget: 'wkscn.name_shoestring_backbone', spat: 'wkscn.name_peering_pressure', cable: 'wkscn.name_cut_and_run', region: 'wkscn.name_planting_flags', island: 'wkscn.name_island_hopper', event: 'wkscn.name_stream_team', flood: 'wkscn.name_flood_week', latency: 'wkscn.name_ludicrous_speed' };
|
||||
const fileFor = (t, key) => { const x = GOALS[t]; return { v: 1, key, theme: x.theme, city: 'fra', cash: 500000, days: 240, lvl: 2, rules: x.rules || {}, mods: [], goal: x.goal, name: { l: NAME[x.theme], p: {} }, desc: x.desc, seed: 42, par: 180, ref: { steps: [] } }; };
|
||||
|
||||
test('generator: deterministic for a week, and every theme a template the game knows', () => {
|
||||
const g = G.game(), a = tmp(), b = tmp();
|
||||
const j1 = G.generate(g, '2027-W10', a), j2 = G.generate(G.game(), '2027-W10', b);
|
||||
assert.deepEqual(j1, j2, 'same key, same scenario');
|
||||
const themes = JSON.parse(g.ev('JSON.stringify(Object.keys(WS_THEMES))')).sort(), goals = JSON.parse(g.ev('JSON.stringify(Object.keys(WS_GOALS))'));
|
||||
assert.deepEqual(Object.keys(G.TEMPLATES).sort(), themes, 'a template for each theme');
|
||||
for (const T of Object.values(G.TEMPLATES)) assert.ok(goals.includes(T.goal), `${T.goal} is a goal type of the game`);
|
||||
assert.deepEqual(g.errors, []);
|
||||
});
|
||||
|
||||
test('every committed week verifies: not won on day 0, the reference wins on its par with time to spare', () => {
|
||||
const g = G.game(), files = committed();
|
||||
assert.ok(files.length >= 3, 'this week and the next two are committed');
|
||||
for (const j of files) {
|
||||
const v = G.verify(g, j);
|
||||
assert.ok(v.ok, `${j.key}: ${v.why}`);
|
||||
assert.equal(v.par, j.par, `${j.key}: par`);
|
||||
assert.ok(j.days >= 180 && j.days <= 365, `${j.key}: ${j.days} days, playable in a sitting or two`);
|
||||
}
|
||||
// Varied: no theme twice in a row, and the weeks start in different parts of the world.
|
||||
for (let i = 1; i < files.length; i++) assert.notEqual(files[i].theme, files[i - 1].theme);
|
||||
assert.equal(new Set(files.map((f) => g.ev(`CITY['${f.city}'].reg`))).size, files.length);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(DIR, 'index.json'), 'utf8')), { v: 1, weeks: G.list(DIR) });
|
||||
assert.deepEqual(g.errors, []);
|
||||
});
|
||||
|
||||
test('the file is checked field by field, and --check rejects a tampered one', () => {
|
||||
const { ev, errors } = load(), j = committed()[0], ok = (x, key = j.key) => ev(`!!wsValid(${JSON.stringify(x)},'${key}')`);
|
||||
assert.equal(ok(j), true);
|
||||
const bad = {
|
||||
'another week': [j, '2020-W01'], 'not a week': [{ ...j, key: '2026-W99' }, '2026-W99'],
|
||||
'unknown field': [{ ...j, x: 1 }], 'old schema': [{ ...j, v: 0 }], 'unknown theme': [{ ...j, theme: 'pirates' }],
|
||||
'unknown city': [{ ...j, city: 'nope' }], 'days': [{ ...j, days: 5000 }], 'cash': [{ ...j, cash: -1 }], 'par after the end': [{ ...j, par: j.days + 1 }],
|
||||
'seed': [{ ...j, seed: 1.5 }], 'unknown rule': [{ ...j, rules: { noTransit: true } }], 'rule value': [{ ...j, rules: { spat: 'yes' } }],
|
||||
'bogus cable pair': [{ ...j, rules: { banPairs: ['nope:a-b'] } }], 'home banned': [{ ...j, rules: { banCities: [j.city] } }],
|
||||
'unknown mod': [{ ...j, mods: ['godmode'] }], 'too many mods': [{ ...j, mods: ['pricey', 'chaos', 'poor'] }],
|
||||
'unknown goal type': [{ ...j, goal: { t: 'win', p: {} } }], 'goal number': [{ ...j, goal: { t: 'served', p: { g: 1e9 } } }],
|
||||
'goal missing a parameter': [{ ...j, goal: { t: 'path', p: { a: 'fra', b: 'nyc', g: 100 } } }],
|
||||
'goal extra parameter': [{ ...j, goal: { t: 'served', p: { g: 100, x: 1 } } }], 'goal city': [{ ...j, goal: { t: 'lat', p: { a: 'fra', b: 'fra', ms: 10, n: 5 } } }],
|
||||
'floods without the flood rule': [{ ...j, rules: {}, goal: { t: 'floods', p: { n: 5, big: 0 } } }],
|
||||
'event after the end': [{ ...j, goal: { t: 'event', p: { city: j.city, g: 100, day: 360, dur: 5 } }, days: 300 }],
|
||||
'name from another theme': [{ ...j, name: { l: 'puzzles_weekly.detour', p: {} } }], 'text with code': [{ ...j, desc: { l: j.desc.l, p: { ...j.desc.p, x: '<b>' } } }],
|
||||
'label placeholder': [{ ...j, desc: { l: j.desc.l, p: Object.fromEntries(Object.keys(j.desc.p).map((k) => [k, 'nope'])) } }],
|
||||
};
|
||||
for (const [why, [x, key]] of Object.entries(bad)) assert.equal(ok(x, key || x.key), false, why);
|
||||
const dir = tmp();
|
||||
for (const f of committed()) fs.writeFileSync(path.join(dir, f.key + '.json'), JSON.stringify(f) + '\n');
|
||||
fs.copyFileSync(path.join(DIR, 'index.json'), path.join(dir, 'index.json'));
|
||||
fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify({ ...j, goal: { t: 'win', p: {} } }));
|
||||
const g = G.game();
|
||||
assert.deepEqual(G.check(g, dir, 0).filter((x) => x.startsWith(j.key)), [`${j.key}: the game rejects it`]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('--check: a week the reference no longer wins is regenerated as a new revision, a new par is just written', () => {
|
||||
const g = G.game(), dir = tmp(), j = committed()[0];
|
||||
fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify({ ...j, par: j.par + 1 }) + '\n');
|
||||
const now = g.ev(`pzWeekStart('${j.key}')`);
|
||||
let r = G.refresh(g, dir, now);
|
||||
assert.ok(r.fixed.includes(`${j.key}: new par ${j.par}`), r.fixed.join('; '));
|
||||
assert.equal(JSON.parse(fs.readFileSync(path.join(dir, j.key + '.json'), 'utf8')).rev, undefined, 'a new par keeps the revision');
|
||||
// A goal its reference plan never reaches: as if a release changed the world under the week.
|
||||
fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify({ ...j, goal: { t: 'pops', p: { cs: ['scl'] } }, ref: { ...j.ref, steps: [] } }) + '\n');
|
||||
r = G.refresh(g, dir, now);
|
||||
const n = JSON.parse(fs.readFileSync(path.join(dir, j.key + '.json'), 'utf8'));
|
||||
assert.equal(n.rev, 2, r.fixed.join('; ') + r.bad.join('; '));
|
||||
assert.ok(G.verify(g, n).ok);
|
||||
// Past weeks keep their files.
|
||||
assert.deepEqual(G.refresh(g, dir, now + 30 * 864e5).fixed, []);
|
||||
assert.deepEqual(G.check(g, dir, now), []);
|
||||
assert.deepEqual(g.errors, []);
|
||||
});
|
||||
|
||||
test('the page never asks for a weekly scenario on load, only when the Scenarios list opens', async () => {
|
||||
const { ev, errors } = load();
|
||||
ev("window.__f=[];window.fetch=(u,o)=>{__f.push(String(u));return Promise.resolve({ok:false,json:()=>Promise.reject()})}");
|
||||
ev("showTitle();for(let i=0;i<5;i++)frame(performance.now()+i*1000);renderAll()");
|
||||
assert.equal(ev("__f.filter(u=>/scenarios/.test(u)).length"), 0, 'nothing on the title screen');
|
||||
ev("ACT.start({});for(let i=0;i<3;i++)dayTick();renderAll()");
|
||||
assert.equal(ev("__f.filter(u=>/scenarios/.test(u)).length"), 0, 'nothing while playing');
|
||||
ev('ACT.scenarios({})');
|
||||
const key = ev('pzWeekKey(new Date())');
|
||||
assert.deepEqual(ev("JSON.stringify(__f.filter(u=>/scenarios/.test(u)))"), JSON.stringify([`scenarios/weekly/${key}.json`]));
|
||||
ev('closeModal();ACT.scenarios({})');
|
||||
assert.equal(ev("__f.filter(u=>/scenarios/.test(u)).length"), 1, 'once is enough while it is loading');
|
||||
await tick();
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the published scenario is played when it is good, the in-browser weekly when it is missing, offline or bad', async () => {
|
||||
const { ev, dom, errors } = load(), key = ev('pzWeekKey(new Date())'), good = { ...committed()[1], key };
|
||||
for (const [how, why] of [
|
||||
["Promise.resolve({ok:false,status:404,json:()=>Promise.reject()})", 'missing'],
|
||||
["Promise.reject(new TypeError('offline'))", 'offline'],
|
||||
["Promise.resolve({ok:true,json:()=>Promise.reject(new SyntaxError('x'))})", 'not JSON'],
|
||||
[`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, city: 'nope' })})})`, 'an unknown city'],
|
||||
[`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, key: '2020-W01' })})})`, 'another week'],
|
||||
]) {
|
||||
ev(`UI.wsWk=null;window.fetch=()=>${how}`); ev('ACT.scenarios({})'); await tick();
|
||||
assert.equal(ev('wsDef()'), null, why);
|
||||
assert.match(dom.window.document.getElementById('wsRow').textContent, new RegExp(ev(`tr('features.weekly_challenge_key',{key:'${key}'})`)), why);
|
||||
ev("document.querySelector('#wsRow [data-act=startWeekly]').click();if(UI.pendGame)ACT.pitchSkip()");
|
||||
assert.equal(ev("S.scn.id==='weekly'&&!S.scn.wk&&S.scn.key"), key, `${why}: the in-browser weekly`);
|
||||
}
|
||||
serveFile(ev, good); ev('ACT.scenarios({})'); await tick();
|
||||
assert.match(dom.window.document.getElementById('wsRow').textContent, new RegExp(ev('wsTxt(wsDef().name)').replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
|
||||
ev("document.querySelector('#wsRow [data-act=startWeekly]').click();if(UI.pendGame)ACT.pitchSkip()");
|
||||
assert.equal(ev('S.scn.wk.key'), key);
|
||||
assert.equal(ev('S.rules.preset'), 'oncall', 'M4: On-call');
|
||||
assert.equal(ev('S.cash'), good.mods.includes('poor') ? 100000 : good.cash);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('every goal type has a progress card, needs play, and wins, streaks and shares', () => {
|
||||
const { ev, dom, errors } = load(), key = ev('pzWeekKey(new Date())');
|
||||
for (const t of Object.keys(GOALS)) {
|
||||
const f = fileFor(t, key);
|
||||
assert.equal(ev(`wsBegin(${JSON.stringify(f)},'T')`), true, t);
|
||||
ev('if(UI.pendGame)ACT.pitchSkip();closeModal();compute();renderAll()');
|
||||
assert.equal(ev('wsOk()'), false, `${t}: not won on day 0`);
|
||||
assert.ok(ev('scnProg().items.length') > 0, `${t}: a progress card`);
|
||||
const card = ev('scnCard()');
|
||||
assert.doesNotMatch(card, /wkscn\.|\{\w+\}|undefined|NaN/, `${t}: ${card}`);
|
||||
if (t === 'event') assert.equal(ev("S.biz.filter(b=>b.type==='event'&&b.start===120&&b.bw===400).length"), 1, 'the event is booked');
|
||||
if (t === 'floods') assert.equal(ev("scnRule('ddos')"), true);
|
||||
}
|
||||
// A win: a POP goal met on day 1, recorded for the week, with a streak and the share line.
|
||||
ev("localStorage.removeItem('sot-wkscn')");
|
||||
ev(`wsBegin(${JSON.stringify(fileFor('pops', key))},'T');if(UI.pendGame)ACT.pitchSkip();closeModal()`);
|
||||
// Waves take a few days to light (real lead times), so the goal is met once they are up.
|
||||
const build = "for(const c of ['ams','par']){UI.via=null;openLinkModal('fra',c);ACT.buildLink({tier:1});closeModal();}for(let i=0;i<90&&!S.scn.done;i++)dayTick()";
|
||||
ev(build);
|
||||
const d = ev('S.scn.done');
|
||||
assert.ok(d > 0 && d < 90, `won on day ${d}`);
|
||||
assert.match(dom.window.document.getElementById('modal').textContent, new RegExp(`Won on day ${d}!`));
|
||||
assert.equal(ev('wsShareText()'), `Series of Tubes weekly ${key} “Island Hopper” won day ${d} (par 180) · seriesoftub.es`);
|
||||
const rec = JSON.parse(ev("localStorage.getItem('sot-wkscn')"));
|
||||
assert.deepEqual(rec.w[key], { d, rv: 1 });
|
||||
assert.equal(rec.streak.n, 1);
|
||||
// Last week won too: the streak grows; a gap starts it again.
|
||||
ev(`localStorage.setItem('sot-wkscn',JSON.stringify({go:{},w:{},streak:{last:pzPrevKey('${key}'),n:3,best:3}}))`);
|
||||
ev(`wsBegin(${JSON.stringify(fileFor('pops', key))},'T');if(UI.pendGame)ACT.pitchSkip();closeModal()`);
|
||||
ev(build);
|
||||
assert.equal(JSON.parse(ev("localStorage.getItem('sot-wkscn')")).streak.n, 4);
|
||||
assert.equal(ev(`wsStreak(wsLoad(),pzKeyAdd('${key}',2))`), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('saves keep the scenario, checked again on load; a tampered one plays on as the in-browser weekly', () => {
|
||||
const { ev, errors } = load(), key = ev('pzWeekKey(new Date())');
|
||||
ev(`wsBegin(${JSON.stringify(fileFor('path', key))},'T');if(UI.pendGame)ACT.pitchSkip();closeModal();S.scn.run=7`);
|
||||
ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()');
|
||||
assert.equal(ev("S.scn.wk.goal.t+':'+S.scn.run+':'+S.scn.home"), 'path:7:fra');
|
||||
ev("S.scn.wk.goal={t:'win',p:{}};S.scn.run='x';S=migrate(JSON.parse(JSON.stringify(S)));compute();renderAll()");
|
||||
assert.equal(ev("S.scn.id+':'+(S.scn.wk===undefined)+':'+(S.scn.run===undefined)"), 'weekly:true:true');
|
||||
ev('for(let i=0;i<3;i++)dayTick();scnCard()');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('weekly scenario in every language and on a 360 px phone, with the door badge until started', async () => {
|
||||
for (const lang of ['de', 'es', 'fr', 'it', 'pt']) {
|
||||
const { ev, dom, errors } = load({ lang }), key = ev('pzWeekKey(new Date())'), doc = dom.window.document;
|
||||
ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));showTitle()");
|
||||
const badge = () => !!doc.querySelector('.door[data-door=scn] .pznew');
|
||||
assert.equal(badge(), true, `${lang}: badge before the week is started`);
|
||||
for (const j of committed()) {
|
||||
serveFile(ev, { ...j, key }); ev('ACT.scenarios({})'); await tick();
|
||||
const row = doc.getElementById('wsRow');
|
||||
assert.doesNotMatch(row.textContent, /wkscn\.|\{\w+\}|undefined|NaN/, `${lang} ${j.key}: no raw labels or placeholders`);
|
||||
assert.notEqual(ev('wsTxt(wsDef().desc)'), ev("(d=>EN[d.l].replace(/\\{(\\w+)\\}/g,(m,k)=>wsVal(k,d.p[k])))(wsDef().desc)"), `${lang}: translated text`);
|
||||
ev("document.querySelector('#wsRow [data-act=startWeekly]').click();if(UI.pendGame)ACT.pitchSkip();closeModal();renderAll()");
|
||||
assert.doesNotMatch(ev('scnCard()'), /wkscn\.|\{\w+\}|undefined|NaN/, `${lang} ${j.key}: card`);
|
||||
}
|
||||
ev('showTitle()');
|
||||
assert.equal(badge(), false, `${lang}: no badge once started`);
|
||||
assert.deepEqual(errors, [], lang);
|
||||
}
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue