Merge save slots: one network per window, consistent saves
This commit is contained in:
commit
efb14680cc
36 changed files with 1099 additions and 134 deletions
|
|
@ -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 };
|
||||
|
|
|
|||
|
|
@ -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));
|
||||
|
|
|
|||
|
|
@ -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, []);
|
||||
});
|
||||
|
||||
|
|
@ -1052,7 +1052,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, []);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -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, []);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -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, []);
|
||||
|
|
|
|||
|
|
@ -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]]) {
|
||||
|
|
@ -221,7 +221,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()");
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
|
|
|
|||
|
|
@ -169,16 +169,18 @@ test('no clock in a puzzle: days never pass, nothing breaks, no bills', () => {
|
|||
|
||||
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)");
|
||||
const before = ev("localStorage.getItem('sot-save-v1')");
|
||||
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("localStorage.getItem('sot-save-v1')"), before, 'untouched while in the puzzle');
|
||||
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');
|
||||
|
|
@ -186,7 +188,7 @@ test('the main save is byte-identical before and after playing and solving a puz
|
|||
assert.equal(ev('S.day'), day);
|
||||
assert.ok(ev('!!S.pops.ams'));
|
||||
assert.equal(ev('UI.started'), true);
|
||||
assert.equal(ev("localStorage.getItem('sot-save-v1')"), before, 'and after');
|
||||
assert.equal(ev("slotRaw(UI.slot||window.__slot)"), before, 'and after');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
|
@ -198,7 +200,7 @@ test('leaving a puzzle with no game goes back to the title screen', () => {
|
|||
assert.equal(ev('S.mode'), 'puzzle');
|
||||
ev('ACT.pzLeave({})');
|
||||
assert.equal(ev('S'), null);
|
||||
assert.equal(ev("localStorage.getItem('sot-save-v1')"), null, 'no main save appeared');
|
||||
assert.equal(ev("slotIdx(true).length"), 0, 'no network was saved');
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /Series/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -354,8 +356,8 @@ test('main-game toasts and leftover buttons do nothing in a puzzle', () => {
|
|||
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);
|
||||
const before = ev("localStorage.getItem('sot-save-v1')");
|
||||
ev("ACT.pzStart({id:'hello'})");
|
||||
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]})");
|
||||
|
|
@ -373,7 +375,7 @@ test('main-game toasts and leftover buttons do nothing in a puzzle', () => {
|
|||
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("localStorage.getItem('sot-save-v1')"), before);
|
||||
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);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
@ -1035,16 +1035,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, []);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
});
|
||||
|
|
@ -335,7 +335,7 @@ test('saves: old saves load with no intern and everything off, settings survive
|
|||
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(localStorage.getItem('sot-save-v1')))");
|
||||
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)`);
|
||||
|
|
|
|||
|
|
@ -86,7 +86,7 @@ test('one-site requests add only A, then a new second site gets exactly its miss
|
|||
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(localStorage.getItem('sot-save-v1')));compute()");
|
||||
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, []);
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ test('redundancy kit matches normal purchases, including cash, monthly costs and
|
|||
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(localStorage.getItem('sot-save-v1')));compute()");
|
||||
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, []);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue