File size: 21,993 Bytes
bad179a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
// Drives the page in headless Chrome (DevTools protocol): node uitest.js <base url> <Linux|Windows> <shots dir> <prefix>
// Only harmless actions on Linux (echo, dialogs, rules); on the Windows edition the stand-in powershell just echoes.
const { spawn } = require('child_process'), fs = require('fs'), os = require('os'), path = require('path');
const [base, edition, out, prefix] = process.argv.slice(2), win = edition === 'Windows', port = 9300 + (process.pid % 500);
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sm-chrome-'));
const chrome = spawn('google-chrome', ['--headless=new', '--no-sandbox', '--password-store=basic', '--disable-gpu', `--remote-debugging-port=${port}`, `--user-data-dir=${dir}`, '--window-size=1500,940', 'about:blank'], { stdio: 'ignore' });
const sleep = ms => new Promise(r => setTimeout(r, ms));
const HELPERS = `
const $ = (sel, root = document) => root.querySelector(sel), $$ = (sel, root = document) => [...root.querySelectorAll(sel)];
const sleep = ms => new Promise(r => setTimeout(r, ms));
const page = () => $('main > section:not([hidden])'), tab = () => $('.tab', page());
const byText = (sel, text, root = document) => $$(sel, root).find(e => e.textContent.trim() === text);
const dlg = () => $('dialog[open]');
const down = el => el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
const type = (el, v) => { el.value = v; el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); };
const rows = (root = tab()) => $$('tbody tr', root).filter(r => !r.hidden);
const until = async (fn, ms = 6000) => { for (const t0 = Date.now(); Date.now() - t0 < ms; await sleep(100)) { const v = fn(); if (v) return v; } return fn(); };
const open = async name => { byText('.tabbar button', name).click(); await until(() => $('.tabbar .on')?.textContent === name && tab()); await sleep(150); };
const answer = async label => { const b = await until(() => dlg() && byText('button', label, dlg())); b.click(); await sleep(150); return true; };
`;
(async () => {
    let target;
    for (let i = 0; i < 50 && !target; ++i) { await sleep(200); try { target = (await (await fetch(`http://127.0.0.1:${port}/json`)).json()).find(t => t.type === 'page'); } catch {} }
    const ws = new WebSocket(target.webSocketDebuggerUrl), pending = new Map(), problems = [];
    let id = 0, failed = 0;
    const send = (method, params = {}) => new Promise(res => { pending.set(++id, res); ws.send(JSON.stringify({ id, method, params })); });
    ws.onmessage = e => {
        const m = JSON.parse(e.data);
        if (m.id) return pending.get(m.id)?.(m.result || m.error);
        if (m.method === 'Runtime.exceptionThrown') problems.push('EXCEPTION ' + (m.params.exceptionDetails.exception?.description || m.params.exceptionDetails.text));
        if (m.method === 'Runtime.consoleAPICalled' && ['error', 'warning'].includes(m.params.type)) problems.push('CONSOLE ' + m.params.args.map(a => a.value ?? a.description).join(' '));
        if (m.method === 'Log.entryAdded' && ['error', 'warning'].includes(m.params.entry.level)) problems.push('LOG ' + m.params.entry.text + ' ' + (m.params.entry.url || ''));
    };
    await new Promise(r => ws.onopen = r);
    await send('Runtime.enable'), await send('Log.enable'), await send('Page.enable');
    const size = (width, height) => send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });
    const shot = async name => fs.writeFileSync(path.join(out, `${prefix}-${name}.png`), Buffer.from((await send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
    const step = async (name, body) => { // body: async function body run in the page; truthy result = pass
        const r = await send('Runtime.evaluate', { expression: `(async () => { ${HELPERS} ${body} })()`, awaitPromise: true, returnByValue: true });
        const v = r.result?.value, okay = !r.exceptionDetails && !!v;
        if (!okay) ++failed;
        console.log(`${okay ? 'PASS' : 'FAIL'}  ${name}${typeof v === 'string' ? '  — ' + v.replace(/\s+/g, ' ').slice(0, 230) : r.exceptionDetails ? '  — ' + (r.exceptionDetails.exception?.description || r.exceptionDetails.text) : ''}`);
    };
    await size(1500, 940);
    await send('Page.navigate', { url: base + '/' });
    await sleep(4500);

    await step('dashboard: cards, tiles, sidebar', `const c = $$('.card'); return c.length === 3 && $$('.item').length === 2 && $$('.tile b', page())[0].textContent === '1 / 2' && document.title + ' | ' + $$('.tile b', page()).map(b => b.textContent).join(' | ')`);
    await step('dashboard: search hides non-matching cards', `type($('input[type=search]', page()), 'unreach'); const hidden = $$('.card').map(c => c.hidden).join(); type($('input[type=search]', page()), ''); return hidden === 'true,false,false' && $$('.card').every(c => !c.hidden)`);
    await step('card context menu', `$$('.card')[0].dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 500, clientY: 300 })); const t = $$('.menu button').map(b => b.textContent).join(', '); byText('.menu button', 'Reconnect').click(); await sleep(300); return !$('.menu') && t === 'Open details, Reconnect, Edit…, Remove…' && t`);
    await sleep(6000);
    await step('open a server from its card', `$$('.card')[0].click(); await until(() => tab()); return location.hash.startsWith('#/server/') && $('h1', page()).textContent === 'This computer' && $('.tabbar .on').textContent === 'Overview' && $('.chips').textContent`);
    await shot('ui-overview');
    const xy = await send('Runtime.evaluate', { expression: `(() => { const r = document.querySelector('.chart').getBoundingClientRect(); return [r.right - 60, r.top + 120]; })()`, returnByValue: true });
    await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: xy.result.value[0], y: xy.result.value[1] });
    await sleep(400), await shot('ui-chart-hover');
    await step('live window select', `const s = $('label.col select', page()); type(s, '5'); return S.span === 5`);

    await step('processes: rows, sort by name, filter', `await open('Processes'); await until(() => rows().length > 3);
        const n = rows().length; byText('th', 'Name').click(); const names = rows().map(r => r.cells[1].textContent), sorted = names.join() === names.toSorted().join();
        type($('input[type=search]', tab()), '${win ? 'sql' : 'systemd'}'); const f = rows().length; type($('input[type=search]', tab()), ''); byText('th', 'CPU').click(); byText('th', 'CPU').click();
        return sorted && f >= 1 && f < n && rows().length === n && tab().querySelector('.muted').textContent + ' | filtered ' + f`);
    await step('processes: action without a selection', `byText('button', 'Priority…', tab()).click(); await sleep(100); return !dlg() && tab().lastChild.textContent === 'Select a process first.'`);
    await step('processes: select a row, context menu', `const r = rows().at(-1); down(r); r.cells[1].dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 600, clientY: 400 }));
        const t = $$('.menu button').map(b => b.textContent).join(', '); document.body.click(); await sleep(100); return rows().some(x => x.classList.contains('sel')) && !$('.menu') && t`);
    if (win) {
        await step('processes: Kill tree asks, then runs the platform command', `byText('button', 'Kill tree', tab()).click(); const q = (await until(dlg)).querySelector('p').textContent; await answer('Yes');
            const s = await until(() => tab().lastChild.textContent.startsWith('✓') && tab().lastChild.textContent); return /^Kill tree .+ \\(\\d+\\) on This computer\\?$/.test(q) && /^✓ taskkill \\/F \\/T \\/PID \\d+$/.test(s) && q + ' -> ' + s`);
        await step('processes: priority dialog', `byText('button', 'Priority…', tab()).click(); const d = await until(dlg), opts = $$('option', d).map(o => o.textContent).join(), cur = $('select', d).value; await answer('OK');
            const s = await until(() => /PriorityClass/.test(tab().lastChild.textContent) && tab().lastChild.textContent); return cur === 'Normal' && /= 'Normal'$/.test(s) && opts + ' -> ' + s`);
    } else {
        await step('processes: confirmation can be declined (nothing runs)', `byText('button', 'Terminate', tab()).click(); const q = (await until(dlg)).querySelector('p').textContent; await answer('No'); await sleep(300);
            return !dlg() && !tab().lastChild.textContent.startsWith('✓') && !tab().lastChild.textContent.startsWith('Running') && q`);
        await step('processes: priority dialog lists the nice values (cancelled)', `byText('button', 'Priority…', tab()).click(); const d = await until(dlg), opts = $$('option', d).map(o => o.textContent).join(' | '), cur = $('select', d).value; await answer('Cancel'); return cur === '0 (normal)' && opts`);
    }
    await step('processes: freeze list stops refreshing', `const c = $('input[type=checkbox]', tab()); c.click(); const a = rows().map(r => r.textContent).join(); await sleep(${win ? 7000 : 4500}); const b = rows().map(r => r.textContent).join(); c.click(); return a === b`);

    await step('services: rows, state filter', `await open('Services'); await until(() => rows().length > 3); const n = rows().length; type($('select', tab()), 'Failed'); const f = rows().length, all = rows().every(r => r.cells[1].textContent === 'failed');
        type($('select', tab()), 'Running'); const run = rows().every(r => r.cells[2].textContent === 'running'); type($('select', tab()), 'All'); return f >= 1 && f < n && all && run && tab().querySelector('.muted').textContent + ' | failed shown: ' + f`);
    if (win) await step('services: Restart asks, then runs', `down(rows().find(r => r.cells[0].textContent === 'BrokenSvc')); byText('button', 'Restart', tab()).click(); const q = (await until(dlg)).querySelector('p').textContent; await answer('Yes');
        const s = await until(() => tab().lastChild.textContent.startsWith('✓') && tab().lastChild.textContent); return s === "✓ Restart-Service -Name 'BrokenSvc' -Force" && q + ' -> ' + s`);
    else await step('services: Start runs without a question only after selection; Stop asks (declined)', `down(rows()[0]); byText('button', 'Stop', tab()).click(); const q = (await until(dlg)).querySelector('p').textContent; await answer('No'); return !dlg() && /^Stop .+ on This computer\\?$/.test(q) && q`);
    await step('services: logs dialog', `byText('button', 'Logs', tab()).click(); const d = await until(dlg), text = await until(() => $('pre', d).textContent !== 'Loading…' && $('pre', d).textContent), title = $('h2', d).textContent;
        await answer('Close'); return !dlg() && title.startsWith('Logs — ') && ${win ? `/Get-WinEvent/.test(text)` : `/journal/.test(text)`} && title`);

    await step('console: run a command, history with arrow keys', `await open('Console'); const i = await until(() => $('input.mono', tab())), key = k => i.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true }));
        i.value = 'echo ui-test-$((40+2))'; key('Enter'); const out = await until(() => $('.console .good, .console .bad') && $('.console').textContent); key('ArrowUp'); const recalled = i.value; key('ArrowDown');
        return i.value === '' && recalled === 'echo ui-test-$((40+2))' && /\\[exit 0 · \\d+ ms\\]/.test(out) && ${win ? `/would run/.test(out)` : `/ui-test-42/.test(out)`} && out.slice(-90)`);
    await step('console: quick diagnostic button', `const b = $$('.side .panel', tab())[0].querySelectorAll('button')[${win ? 2 : 8}], n = $$('.console .good, .console .bad').length; b.click(); await until(() => $$('.console .good, .console .bad').length > n, 9000);
        return $$('.console .good, .console .bad').length > n && b.textContent + ': ' + b.title.slice(0, 60)`);
    await step('console: system actions ask first (declined)', `const b = byText('button', 'Reboot', tab()), n = $$('.console .cmd').length; b.click(); const q = (await until(dlg)).querySelector('p').textContent; await answer('No'); await sleep(200);
        return $$('.console .cmd').length === n && b.classList.contains('danger') && /unavailable/.test(q) && q`);
    await shot('ui-console');

    await step('rules: add a rule through the dialog', `await open('Alert rules'); await until(() => rows($('.table', tab())).length === 7); byText('button', '+ Add rule', tab()).click(); const d = await until(dlg), sel = $$('select', d), num = $$('input[type=number]', d);
        const metrics = $$('option', sel[0]).length; type(sel[0], 'procs'); type(num[0], '100000'); type(num[1], '0'); type(sel[3], 'command'); const argOn = !$('.form input:not([type])', d).disabled, hint = $('.form input:not([type])', d).placeholder; type(sel[3], 'notify');
        const argOff = $('.form input:not([type])', d).disabled; await answer('OK'); const ok = await until(() => rows($('.table', tab())).length === 8);
        return ok && argOn && argOff && metrics === ${win ? 13 : 14} && rows($('.table', tab())).at(-1).cells[1].textContent + ' | hint: ' + hint`);
    await step('rules: toggle, edit, delete', `const t = $('.table', tab()), last = () => rows(t).at(-1); last().querySelector('input').click(); await until(() => cur().cfg.rules.at(-1).enabled === false);
        down(last()); byText('button', 'Edit', tab()).click(); const d = await until(dlg), title = $('h2', d).textContent, val = $$('input[type=number]', d)[0].value; await answer('Cancel');
        byText('button', 'Delete', tab()).click(); const gone = await until(() => rows(t).length === 7); return gone && title === 'Edit rule' && val === '100000' && cur().cfg.rules.length === 7`);
    await step('rules: reset to defaults', `byText('button', 'Reset to defaults', tab()).click(); await answer('Yes'); await sleep(1500); return cur().cfg.rules.length === 7 && $$('.table', tab())[1].textContent`);

    await step('insights: analysis, heatmap, autopilot form saves', `await open('Insights & Autopilot'); await until(() => $('.heat i', tab())); const n = $$('input[type=number]', tab())[3]; type(n, '33'); await until(() => cur().cfg.autopilot.runawayMinutes === 33);
        const dry = $$('input[type=checkbox]', tab())[1].checked; byText('button', 'Analyze now', tab()).click(); await sleep(1200);
        return dry && cur().cfg.autopilot.dryRun && $$('.heat i', tab()).length === 168 && $$('.tile', tab()).length === 6 && $$('.finding', tab()).length + ' finding(s): ' + $$('.finding b', tab()).map(b => b.textContent).join('; ')`);
    await step('insights: manual fix asks first (declined)', `const b = $('.finding button', tab()); if (!b) return 'no finding with an action right now'; b.click(); const q = (await until(dlg)).querySelector('p').textContent; await answer('No'); return !b.disabled && q`);
    await shot('ui-insights');

    await step('history: ranges and export link', `await open('History'); await until(() => /Resolution/.test(tab().textContent)); byText('button', '1 h', tab()).click(); const r = await until(() => /every sample/.test(tab().textContent) && $('.muted', tab()).textContent);
        byText('button', 'All', tab()).click(); await sleep(800); return r && $('a.button', tab()).href.endsWith('range=0') && rows().length === ${win ? 13 : 14} && r`);
    await step('header: pause / resume', `byText('button', '❚❚ Pause', page()).click(); const p = await until(() => $('.state', page()).textContent === '● Paused'); byText('button', '▶ Resume', page()).click(); return p && await until(() => $('.state', page()).textContent === '● Online')`);
    await step('header: power menu', `byText('button', '⏻ Power', page()).click(); const t = $$('.menu button').map(b => b.textContent).join(', '); await sleep(50); byText('.menu button', 'Reboot…').click(); const q = (await until(dlg)).querySelector('p').textContent; await answer('No'); return !$('.menu') && t === 'Reboot…, Shut down…, Remove from monitor…' && q`);
    await step('edit server dialog saves', `byText('button', 'Edit', page()).click(); const d = await until(dlg), f = $$('.form input', d), name = f[0].value, sudo = !!byText('label', 'Run control commands with sudo -n (needs passwordless sudo)', d);
        type(f.at(-1), 'note from the ui test'); const disabled = f[2].disabled && f[4].disabled; await answer('Save'); await until(() => !dlg()); await until(() => cur().cfg.notes === 'note from the ui test');
        return name === 'This computer' && disabled && sudo === ${!win} && cur().cfg.notes === 'note from the ui test' && cur().cfg.autopilot.dryRun && 'sudo option shown: ' + sudo`);

    await step('add a server through the dialog (test connection first)', `byText('aside button', '+ Add').click(); const d = await until(dlg), sel = $('select', d), f = $$('.form input', d); const sshHint = $('.col > .muted', d).textContent; byText('button', 'Save', d).click(); const err = await until(() => $('.col > .row .grow', d).textContent);
        type(sel, '0'); const localHint = $('.col > .muted', d).textContent, auto = f[0].value; type(f[0], 'ui-added'); byText('button', 'Test connection', d).click(); const res = await until(() => /^[✓✗]/.test($('.col > .row .grow', d).textContent) && $('.col > .row .grow', d).textContent, 25000);
        return !!dlg() && err === 'Please enter a name and an address.' && auto === 'This computer' && /No setup needed/.test(localHint) && res.startsWith('✓') && sshHint.slice(0, 60) + ' … | ' + res`);
    if (win) await step('save the new server: it opens; then take it off the list again', `await answer('Save'); const opened = await until(() => S.servers.length === 3 && $('h1', page()).textContent === 'ui-added' && cur()?.online, 12000);
        byText('aside button', 'Remove').click(); await answer('Remove + delete history'); return opened && await until(() => S.servers.length === 2 && S.page === 'dashboard')`);
    else await step('cancel the add dialog (a new server would start without dry run)', `await answer('Cancel'); return !dlg() && S.servers.length === 2`);
    await step('sidebar: context menu, reorder', `$$('.item')[1].dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 100, clientY: 290 })); const t = $$('.menu button').map(b => b.textContent).join(', '); byText('.menu button', 'Move up').click();
        const moved = await until(() => S.servers[0].cfg.name === 'unreachable' && $$('.item b')[0].textContent === 'unreachable'); $$('.item')[0].dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 100, clientY: 220 })); byText('.menu button', 'Move down').click();
        return moved && await until(() => S.servers[0].cfg.name === 'This computer') && t`);
    await step('remove dialog offers both choices (cancelled)', `location.hash = '#/server/0/overview'; await until(() => cur() && tab()); byText('aside button', 'Remove').click(); const d = await until(dlg), t = $$('button', d).map(b => b.textContent).join(' | '), q = $('p', d).textContent; await answer('Cancel'); return S.servers.length === 2 && q + ' ' + t`);

    await step('events page: list, filter, badge', `const unseen = $('.nav .badge').textContent; $$('.nav')[1].click(); await until(() => location.hash === '#/events' && rows(page()).length > 0); await sleep(200); const n = rows(page()).length, kind = rows(page())[0].cells[2].textContent; type($('select', page()), kind.toLowerCase()); const crit = rows(page()).every(r => r.cells[2].textContent === kind), c = rows(page()).length;
        type($('select', page()), 'All events'); const info = n + ' events, ' + c + ' of type ' + kind + ', unseen badge was "' + unseen + '", hidden now: ' + $('.nav .badge').hidden + '; ' + $('.muted', page()).textContent.slice(0, 60);
        if (!($('.nav .badge').hidden && crit && c >= 1 && c <= n)) throw new Error(info); return info`);
    await shot('ui-events');
    await step('events: clear list', `byText('button', 'Clear list', page()).click(); return await until(() => rows(page()).length === 0) && S.alerts.length === 0`);
    await step('unknown hash falls back to the dashboard; tab by hash', `location.hash = '#/server/nope/cpu'; await sleep(300); const a = !$('main > section').hidden; location.hash = '#/server/1/network'; await sleep(1500); return a && $('h1', page()).textContent === 'unreachable' && $('.tabbar .on').textContent === 'Network'`);

    await size(1100, 700), await sleep(500);
    await step('1100 px wide: no horizontal overflow, canvases redrawn at the new size', `location.hash = '#/server/0/overview'; await sleep(2500); const fit = document.documentElement.scrollWidth <= innerWidth && page().scrollWidth <= page().clientWidth + 1;
        const cv = $$('.cv', page()).filter(c => c.clientWidth); return fit && cv.length >= 10 && cv.every(c => c.firstChild.width === Math.round(c.clientWidth * devicePixelRatio)) && innerWidth + 'x' + innerHeight + ', ' + cv.length + ' canvases'`);
    await shot('ui-1100-overview');
    await step('1100 px wide: dashboard', `location.hash = '#/dashboard'; await sleep(1200); return document.documentElement.scrollWidth <= innerWidth && $$('.card').length === 3`);
    await shot('ui-1100-dashboard');
    await step('page escapes server data (no HTML from data in the DOM)', `return !document.querySelector('main script, main img, aside script') && document.querySelectorAll('img').length === 1`);
    const expected = problems.filter(p => /status of 400 .*\/api\/server\/add/.test(p)), other = problems.filter(p => !expected.includes(p)); // the refused empty form
    console.log(other.length || expected.length !== 1 ? 'BROWSER PROBLEMS:\n' + problems.join('\n') : 'no console errors, warnings or exceptions in the browser (besides the one expected 400 of the refused empty form)');
    console.log(failed ? `${failed} step(s) FAILED` : 'all UI steps passed');
    chrome.kill(), ws.close();
    await sleep(300), fs.rmSync(dir, { recursive: true, force: true }), process.exit(failed || other.length ? 1 : 0);
})();