Files
myrzx_bot/frontend/tests/controller.test.mjs
T

330 lines
18 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import {readFile} from 'node:fs/promises';
import {createContext, runInContext} from 'node:vm';
import {shallowReactive, isReactive} from 'vue';
// Exercise orchestration with fake APIs and time. No server or game is contacted.
const source = await readFile(new URL('../src/controller.js', import.meta.url), 'utf8');
const dom = await readFile(new URL('../../ranch_web/static/dom.js', import.meta.url), 'utf8');
const paths = await readFile(new URL('../../ranch_web/static/paths.js', import.meta.url), 'utf8');
const keys = ['login','incubator','bag','ranch','daily','hatching','mainline','battles','gifts','commissions','exploration','maps','statistics','plans','yields'];
const plain = value => JSON.parse(JSON.stringify(value));
const settle = async () => { for (let i = 0; i < 40; i++) await Promise.resolve(); };
function deferred() {
let resolve, reject;
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
return {promise, resolve, reject};
}
class Element extends EventTarget {
constructor(tag = 'div') {
super(); Object.assign(this, {tagName:tag.toUpperCase(), children:[], dataset:{}, value:'', hidden:false, isConnected:true, textContent:'', attributes:{}});
this.classList = {add(){}, toggle(){}};
}
append(...nodes) { this.children.push(...nodes); }
replaceChildren(...nodes) { this.children = nodes; }
setAttribute(key, value) { this.attributes[key] = value; }
querySelector(selector) { return selector === ':invalid' ? this.invalid : null; }
querySelectorAll() { return []; }
remove() { this.isConnected = false; }
focus() {}
click() {}
close() { this.open = false; }
}
async function fixture(t) {
const h = {calls:[], pages:[], notices:[], confirms:[], files:[], overrides:{}, now:100000, timers:new Map(), timerId:0};
h.accounts = new Map(['a', 'b'].map(id => [id, {id, label:id, connected:true, running:false, demo:true, revision:0, player:{name:id}}]));
h.configs = new Map(['a', 'b'].map(id => [id, {interval:30, policy:{egg_rules:{}}, log_visible:true, log_sizes:[420,140]}]));
h.base = {
auth:() => ({required:false, access_mode:'local'}), meta:() => ({version:'2.0.0', nested:{}}), schema:() => ({pages:[]}),
accounts:() => [...h.accounts.values()].map(value => structuredClone(value)),
config:id => ({config:structuredClone(h.configs.get(id)), revision:h.accounts.get(id).revision}),
save:(id, config) => { h.configs.set(id, structuredClone(config)); h.accounts.get(id).revision++; return h.base.config(id); },
status:id => structuredClone(h.accounts.get(id)),
view:(id, key) => ({data:{columns:[{key:'id'}], rows:[], marker:`${id}/${key}`}, loading:false}),
action:(id, operation) => {
if (operation === 'start' || operation === 'stop') h.accounts.get(id).running = operation === 'start';
return {id:`${id}/${operation}`, status:'succeeded', result:{}};
},
logs:() => ({entries:[], next:0}),
remove:id => { h.accounts.delete(id); },
job:() => ({status:'succeeded', result:{}}),
};
const api = new Proxy({}, {get:(_, name) => (...args) => {
h.calls.push({name, args:structuredClone(args), at:h.now});
return Promise.resolve().then(() => {
const fn = h.overrides[name] || h.base[name];
if (!fn) throw new Error(`Unexpected API call: ${String(name)}`);
return fn(...args);
});
}});
class PageView {
constructor(account, key, options) {
Object.assign(this, {account, key, options, root:new Element(), query:{}, data:null, renders:[], selected:[]});
this.login = key === 'login' ? {clearPassword(){}, update(){}} : null;
h.pages.push(this);
}
render(data) { this.data = data; this.renders.push(data); }
clearError() {}
showError(message) { this.error = message; }
selectedRows() { return this.selected; }
destroy() { this.destroyed = true; }
}
const document = Object.assign(new EventTarget(), {
hidden:false, body:new Element('body'), activeElement:null,
querySelector:selector => {
if (selector.startsWith('meta[')) return null;
if (selector === '#action-dialog') return {open:true, close(){}};
if (selector === '#notice') return null;
throw new Error(`Unexpected shell DOM query: ${selector}`);
},
querySelectorAll:() => [], createElement:tag => new Element(tag), createTextNode:text => Object.assign(new Element(), {textContent:text}),
});
const context = createContext({
shallowReactive, api, PageView, PAGES:keys.map(key => [key,key]), document, window:new EventTarget(),
location:{origin:'http://console.invalid', replace:target => { h.redirect = target; }},
structuredClone, AbortController, URL, Blob, Node:Element,
Date:class extends Date { static now() { return h.now; } },
setTimeout:(callback, delay = 0) => { const id = ++h.timerId; h.timers.set(id, {callback, at:h.now + delay}); return id; },
clearTimeout:id => h.timers.delete(id),
notice:(message, error) => h.notices.push({message,error}),
confirm:() => Promise.resolve(h.confirms.length ? h.confirms.shift() : true),
dialog:() => Promise.resolve(h.confirms.length ? h.confirms.shift() : null),
filePicker:() => Promise.resolve(h.files.shift() || null), fileBase64:async () => 'Zml4dHVyZQ==',
request:async path => { h.detailPath = path; return {details:{safe:true}}; },
});
runInContext(dom.replace(/^export /gm, ''), context);
runInContext(paths.replace(/^export /gm, ''), context);
runInContext(source.replace(/^import .+;\r?\n/gm, '').replace('export function createConsoleController', 'function createConsoleController'), context);
h.controller = runInContext('createConsoleController()', context);
h.document = document;
h.context = context;
h.advance = async duration => {
const until = h.now + duration;
for (;;) {
const next = [...h.timers].filter(([,timer]) => timer.at <= until).sort((a,b) => a[1].at - b[1].at)[0];
if (!next) break;
h.now = next[1].at; h.timers.delete(next[0]); next[1].callback(); await settle();
}
h.now = until; await settle();
};
h.findPage = (key, id = h.controller.state.activeId) => h.pages.find(page => page.key === key && page.account.id === id);
t.after(() => h.controller.dispose());
await h.controller.init(new Element()); await settle();
assert.equal(h.controller.state.error, null);
assert.equal(h.controller.state.ready, true);
return h;
}
test('exports the contract, keeps snapshots raw and skips APIs on shell pages', async t => {
const h = await fixture(t), c = h.controller;
assert.deepEqual(Object.keys(c).sort(), ['state','init','navigate','selectAccount','command','refresh','setInterval','retrySave','setLogDebug','inspectLog','dispose'].sort());
assert.ok(isReactive(c.state));
assert.equal(isReactive(c.state.accounts), false);
assert.equal(isReactive(c.state.meta.nested), false);
assert.equal(c.state.currentConfig.policy, undefined);
assert.ok(Object.isFrozen(c.state.currentConfig));
for (const key of ['overview','accounts','activity','system']) await c.navigate(key);
assert.equal(h.calls.filter(call => call.name === 'view').length, 0);
for (const key of keys) await c.navigate(key);
assert.deepEqual(h.calls.filter(call => call.name === 'view').map(call => call.args[1]), keys);
});
test('serializes edits added during an in-flight save and renders only the visible page', async t => {
const h = await fixture(t), c = h.controller, pending = deferred();
await c.navigate('bag'); const bag = h.findPage('bag');
await c.navigate('hatching'); const page = h.findPage('hatching');
const hiddenRenders = bag.renders.length;
h.overrides.save = (id, config) => h.calls.filter(call => call.name === 'save').length === 1 ? pending.promise : h.base.save(id, config);
c.setInterval(60); const saving = c.retrySave(); await settle();
c.setInterval(120); await settle();
assert.equal(h.calls.filter(call => call.name === 'save').length, 1);
pending.resolve({config:{...h.configs.get('a'), interval:60}, revision:1});
await saving; await settle();
const saves = h.calls.filter(call => call.name === 'save');
assert.deepEqual(saves.map(call => call.args[1].interval), [60,120]);
assert.equal(c.state.currentConfig.dirty, false);
assert.equal(c.state.interval, 120);
assert.equal(bag.renders.length, hiddenRenders);
assert.ok(page.renders.length > 1);
await c.navigate('bag');
assert.ok(bag.renders.length > hiddenRenders);
});
test('conflict rebasing retains explicit edits and respects server defaults and linked rules', async t => {
const h = await fixture(t), c = h.controller;
await c.navigate('bag'); const page = h.findPage('bag');
page.options.edit(page.account, ['policy','egg_rules','7','enabled'], true, {}, {
rule_path:['policy','egg_rules','7'], rule_defaults:{action:'feed', priority:1},
});
h.overrides.save = () => Promise.reject(Object.assign(new Error('conflict'), {status:409}));
h.configs.set('a', {interval:30, policy:{external:true, egg_rules:{7:{action:'feed', priority:8}}}});
h.accounts.get('a').revision = 8;
await c.retrySave();
assert.ok(c.state.saveError);
assert.equal(c.state.currentConfig.dirty, true);
h.overrides.save = h.base.save;
await c.retrySave();
const policy = h.configs.get('a').policy;
assert.deepEqual(plain(policy.egg_rules[7]), {action:'feed', priority:8, enabled:true});
assert.equal(policy.feed, true); assert.equal(policy.collect, true); assert.equal(policy.external, true);
assert.equal(c.state.saveError, null);
});
test('stop suppresses an unsent start waiting for a save after switching accounts', async t => {
const h = await fixture(t), c = h.controller, pending = deferred();
h.overrides.save = () => pending.promise;
c.setInterval(60); const saving = c.retrySave(); await settle();
const starting = c.command('start', 'a'); await settle();
await c.selectAccount('b');
await c.command('stop', 'a');
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['a','stop']]);
pending.resolve({config:{...h.configs.get('a'), interval:60}, revision:1});
await Promise.all([saving, starting]);
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['a','stop']]);
assert.equal(c.state.accounts.find(account => account.id === 'a').running, false);
assert.equal(c.state.activeId, 'b');
});
test('a delayed start stays bound to its original account when switching accounts without stop', async t => {
const h = await fixture(t), c = h.controller, pending = deferred();
h.overrides.save = () => pending.promise;
c.setInterval(60); const saving = c.retrySave(); await settle();
const starting = c.command('start', 'a'); await settle();
await c.selectAccount('b');
assert.equal(h.calls.filter(call => call.name === 'action').length, 0);
pending.resolve({config:{...h.configs.get('a'), interval:60}, revision:1});
await Promise.all([saving, starting]);
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['a','start']]);
assert.equal(c.state.activeId, 'b');
});
test('discards hidden-page responses and coalesces generation changes without overlapping views', async t => {
const h = await fixture(t), c = h.controller, pending = deferred();
let reads = 0;
h.overrides.view = () => ++reads === 1 ? pending.promise : {data:{marker:'fresh'}};
const navigation = c.navigate('bag'); await settle(); const page = h.findPage('bag');
page.query.search = 'new'; page.generation = 1;
const reloading = page.options.load(page, true); await settle(); assert.equal(reads, 1);
pending.resolve({data:{marker:'stale'}}); await Promise.all([navigation,reloading]);
assert.deepEqual(page.renders.map(data => data.marker), ['fresh']);
const hidden = deferred(); h.overrides.view = () => hidden.promise;
const second = c.navigate('ranch'); await settle(); await c.navigate('overview');
hidden.resolve({data:{marker:'hidden'}}); await second;
assert.equal(h.findPage('ranch').renders.length, 0);
});
test('removes the captured account without changing a newer selection, then selects after active removal', async t => {
const h = await fixture(t), c = h.controller, confirmation = deferred();
h.confirms.push(confirmation.promise);
const removing = c.command('remove-account', 'a'); await settle();
await c.selectAccount('b'); confirmation.resolve(true); await removing;
assert.equal(c.state.activeId, 'b');
assert.deepEqual(plain(c.state.accounts.map(account => account.id)), ['b']);
await c.command('remove-account', 'b');
assert.equal(c.state.activeId, null);
assert.equal(c.state.accounts.length, 0);
assert.equal(c.state.page, 'login');
const second = await fixture(t);
await second.controller.command('remove-account', 'a');
assert.equal(second.controller.state.activeId, 'b');
assert.equal(second.controller.state.page, 'login');
});
test('stop suppresses an unsent start waiting for an unselected account config', async t => {
const h = await fixture(t), c = h.controller, config = deferred();
h.overrides.config = id => id === 'b' ? config.promise : h.base.config(id);
const starting = c.command('start', 'b'); await settle();
assert.equal(h.calls.filter(call => call.name === 'config' && call.args[0] === 'b').length, 1);
assert.equal(h.calls.filter(call => call.name === 'action').length, 0);
await c.command('stop', 'b');
config.resolve(h.base.config('b')); await starting;
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['b','stop']]);
assert.equal(c.state.accounts.find(account => account.id === 'b').running, false);
assert.equal(c.state.activeId, 'a');
});
test('starting is synchronous and an older start cannot clear a newer pending start', async t => {
const h = await fixture(t), c = h.controller, config = deferred(), response = deferred();
const summary = () => c.state.accounts.find(account => account.id === 'b');
h.overrides.config = id => id === 'b' ? config.promise : h.base.config(id);
h.overrides.action = (id, operation) => operation === 'start' ? response.promise : h.base.action(id, operation);
const first = c.command('start', 'b');
assert.equal(summary().starting, true);
assert.equal(summary().running, false);
const stopping = c.command('stop', 'b');
assert.equal(summary().starting, false);
const second = c.command('start', 'b');
assert.equal(summary().starting, true);
await stopping;
config.resolve(h.base.config('b')); await first; await settle();
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['b','stop'],['b','start']]);
assert.equal(summary().starting, true);
assert.equal(summary().running, false);
h.accounts.get('b').running = true;
response.resolve({id:'latest-start', status:'succeeded', result:{}}); await second;
assert.equal(summary().starting, false);
assert.equal(summary().running, true);
});
test('stop on another account does not suppress a delayed start', async t => {
const h = await fixture(t), c = h.controller, pending = deferred();
h.overrides.save = () => pending.promise;
c.setInterval(60); const saving = c.retrySave(); await settle();
const starting = c.command('start', 'a'); await settle();
await c.command('stop', 'b');
pending.resolve({config:{...h.configs.get('a'), interval:60}, revision:1});
await Promise.all([saving, starting]);
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['b','stop'],['a','start']]);
});
test('stop preserves server tracking for a start whose request was already sent', async t => {
const h = await fixture(t), c = h.controller, response = deferred();
h.overrides.action = (id, operation) => operation === 'start' ? response.promise : h.base.action(id, operation);
h.overrides.job = () => ({id:'sent-start', status:'succeeded', result:{outcome:'server-result'}});
const starting = c.command('start', 'a'); await settle();
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['a','start']]);
await c.command('stop', 'a');
response.resolve({id:'sent-start', status:'queued', operation:'start'});
assert.deepEqual(plain(await starting), {outcome:'server-result'});
assert.equal(h.calls.filter(call => call.name === 'job' && call.args[1] === 'sent-start').length, 1);
assert.deepEqual(h.calls.filter(call => call.name === 'action').map(call => call.args.slice(0,2)), [['a','start'],['a','stop']]);
});
test('jobs finish independently of blocked summaries; disposing rejects no unhandled job promises', async t => {
const h = await fixture(t), c = h.controller, summaries = deferred();
h.overrides.accounts = () => summaries.promise;
h.overrides.action = () => ({id:'job', status:'queued', operation:'stop'});
let polls = 0;
h.overrides.job = () => ++polls === 1 ? {id:'job',status:'running'} : {id:'job',status:'succeeded',result:{}};
const stopping = c.command('stop', 'a'); await settle();
assert.equal(c.state.jobs.length, 1);
await h.advance(1000); await stopping;
assert.equal(c.state.jobs.length, 0);
await h.advance(7000);
assert.equal(h.calls.filter(call => call.name === 'accounts').length, 2);
h.overrides.job = () => ({id:'job',status:'running'});
const disposedCommand = c.command('stop', 'b'); await settle();
c.dispose(); await disposedCommand; await settle();
const count = h.calls.length; await h.advance(20000); assert.equal(h.calls.length, count);
assert.equal(h.timers.size, 0);
summaries.resolve([]); await settle();
});
test('caps logs at 500, discards old debug responses and pauses hidden-document page and log reads', async t => {
const h = await fixture(t), c = h.controller, pending = deferred();
h.overrides.logs = (_, after, debug) => debug ? {entries:Array.from({length:650}, (_, id) => ({id, message:'debug'})), next:650} : pending.promise;
await h.advance(3000);
const debug = c.setLogDebug(true); await settle();
pending.resolve({entries:[{id:9000,message:'old'}],next:9001}); await debug;
assert.equal(c.state.logs.length, 500);
assert.equal(c.state.logs.some(entry => entry.message === 'old'), false);
assert.equal(c.state.logs[0].id, 150);
await c.navigate('bag'); h.document.hidden = true;
const before = h.calls.filter(call => call.name === 'view' || call.name === 'logs').length;
await h.advance(16000);
assert.equal(h.calls.filter(call => call.name === 'view' || call.name === 'logs').length, before);
});