598 lines
32 KiB
JavaScript
598 lines
32 KiB
JavaScript
// The Tests tool window: the project's tests as a tree (PHPUnit suites -> files -> classes -> methods -> data sets, Pest,
|
|
// JumPHP game tests, node --test / vitest / jest), found by reading the files (tests.discover), run all / a suite / a file /
|
|
// a class / a method / the failed ones / the one at the cursor, the project's way (ide/src/UnitTests/TestCommand.php),
|
|
// results live (TeamCity), a summary bar, the failure with a side-by-side diff of expected / actual, the stack's
|
|
// file:line links, what the test printed, a game test's filmed frames, the last runs, coverage in the editor's gutter.
|
|
// The ▶ of the gutter (gutter-run.js) asks it for the marks of a test file and their last result.
|
|
import { backend } from './backend.js';
|
|
import { el, clear, icon, menu, prefs, notify, basename, debounce, t } from './ui.js';
|
|
import { monaco, pathOf } from './editor.js';
|
|
import { worst, counts, sideBySide, phpTestMarks, fileIndex, duration, locations } from './tests-model.js';
|
|
|
|
const SLOW_MS = 500;
|
|
const STATUS_ICON = { passed: '✔', failed: '✘', error: '✘', skipped: '↩', running: '◌', queued: '·' };
|
|
|
|
export class TestsPanel {
|
|
constructor(app) {
|
|
this.app = app;
|
|
this.scopes = [];
|
|
this.index = new Map(); // path -> {scope, file}
|
|
this.results = new Map(); // test id (with its data set) -> result of the last run that ran it
|
|
this.byTest = new Map(); // test id (without data set) -> [result ids]
|
|
this.open = new Set(prefs.get('tests.open', []));
|
|
this.selected = null; // a tree node key
|
|
this.run = null; // {id, scope, selection, coverage, started, count, done, output}
|
|
this.lastRun = null; // {scope, selection, coverage}: Rerun, re-run on save
|
|
this.history = []; // the last runs of this session: {time, label, counts, seconds, coverage, results, films, frames, output}
|
|
this.shown = null; // the run of the history shown (null: the live state)
|
|
this.coverage = null;
|
|
this.showCoverage = true;
|
|
this.films = {};
|
|
this.frames = {};
|
|
this.output = '';
|
|
this.filter = prefs.get('tests.filter', 'all'); // all | failed | slow
|
|
this.onSave = prefs.get('tests.onSave:' + app.projectKey, false);
|
|
this.node = el('div.tests-win');
|
|
this.coverageDecorations = new Map();
|
|
this.redraw = debounce(() => this.render(), 120);
|
|
backend.on('tests.progress', (p) => this.progress(p));
|
|
backend.on('tests.exit', (p) => this.exited(p));
|
|
app.editors.on('saved', (path) => this.saved(path));
|
|
for (const group of app.editors.groups) this.attach(group.editor);
|
|
monaco.editor.onDidCreateEditor((editor) => this.attach(editor));
|
|
this.render();
|
|
this.discover();
|
|
}
|
|
|
|
title() { return t('Tests'); }
|
|
shown() { if (!this.scopes.length) this.discover(); }
|
|
|
|
actions() {
|
|
const running = !!this.run;
|
|
return [
|
|
el('button', { 'data-tour': 'tests-run-all', title: t('Run all tests'), disabled: running || !this.scopes.length, onclick: () => this.runAll() }, icon('play')),
|
|
el('button', { title: t('Rerun the failed tests'), disabled: running || !this.failedIds().length, onclick: () => this.runFailed() }, icon('refresh')),
|
|
el('button', { title: t('Run all tests with coverage'), disabled: running || !this.scopes.some((s) => this.coverable(s)), onclick: () => this.runAll(true) }, icon('check')),
|
|
el('button', { title: t('Stop'), disabled: !running, onclick: () => this.stop() }, icon('stop')),
|
|
el(`button${this.onSave ? '.on' : ''}`, { title: t('Rerun the last tests when a file is saved'), onclick: () => { this.onSave = !this.onSave; prefs.set('tests.onSave:' + this.app.projectKey, this.onSave); this.app.refreshToolHeader?.('tests'); } }, icon('history')),
|
|
el('button', { title: t('Find the tests again'), onclick: () => this.discover() }, icon('search')),
|
|
];
|
|
}
|
|
|
|
// discovery ----------------------------------------------------------------------------------------------
|
|
|
|
async discover() {
|
|
try {
|
|
const { scopes } = await backend.invoke('tests.discover');
|
|
this.scopes = scopes || [];
|
|
this.index = fileIndex(this.scopes);
|
|
} catch (e) {
|
|
this.scopes = [];
|
|
this.error = e.message;
|
|
}
|
|
this.render();
|
|
this.app.gutterRun?.rescan?.();
|
|
}
|
|
|
|
coverable(scope) { return scope && ['phpunit', 'pest'].includes(scope.type); }
|
|
|
|
/** the scope a project file belongs to (a test file of the tree) */
|
|
scopeOf(path) { return this.index.get(path)?.scope || null; }
|
|
|
|
/**
|
|
* The marks of the editor's gutter for a test file: classes and test methods (read from the text, its lines as they
|
|
* are now), JavaScript / Pest tests (the discovered lines), with the last status of each.
|
|
*/
|
|
marksFor(path, text) {
|
|
const entry = this.index.get(path);
|
|
if (!entry) return [];
|
|
const marks = /\.php$/.test(path) && !(entry.file.tests || []).length ? phpTestMarks(text) : (entry.file.tests || []).map((x) => ({ line: x.line, id: x.id, kind: 'method', name: x.name }));
|
|
return marks.map((m) => ({ ...m, status: m.kind === 'class' ? this.statusOf('class', m.id) : this.statusOf('test', m.id) }));
|
|
}
|
|
|
|
// running ------------------------------------------------------------------------------------------------
|
|
|
|
runAll(coverage = false) {
|
|
const scopes = coverage ? this.scopes.filter((s) => this.coverable(s)) : this.scopes;
|
|
if (scopes.length === 1) return this.start(scopes[0], {}, coverage);
|
|
// several scopes: one after the other
|
|
this.queue = scopes.slice(1).map((s) => [s, {}, coverage]);
|
|
if (scopes[0]) this.start(scopes[0], {}, coverage);
|
|
}
|
|
|
|
failedIds() {
|
|
return [...this.results.values()].filter((r) => r.status === 'failed' || r.status === 'error').map((r) => r.id);
|
|
}
|
|
|
|
runFailed() {
|
|
const byScope = new Map();
|
|
for (const r of [...this.results.values()].filter((x) => x.status === 'failed' || x.status === 'error')) {
|
|
const scope = this.scopes.find((s) => s.id === r.scope);
|
|
if (!scope) continue;
|
|
if (!byScope.has(scope)) byScope.set(scope, []);
|
|
byScope.get(scope).push(r.id);
|
|
}
|
|
const list = [...byScope.entries()].map(([scope, ids]) => [scope, { tests: ids }, false]);
|
|
if (!list.length) return;
|
|
this.queue = list.slice(1);
|
|
this.start(...list[0]);
|
|
}
|
|
|
|
/** Ctrl+Shift+F10 in a test file: the test method at the cursor (or its class, or the file); false when it is not one */
|
|
runAtCursor() {
|
|
const editor = this.app.editors.editor?.();
|
|
const model = editor?.getModel();
|
|
if (!model) return false;
|
|
const path = pathOf(model.uri);
|
|
const scope = this.scopeOf(path);
|
|
if (!scope) return false;
|
|
const line = editor.getPosition()?.lineNumber || 1;
|
|
const marks = this.marksFor(path, model.getValue()).filter((m) => m.line <= line + 1);
|
|
const mark = marks[marks.length - 1];
|
|
this.app.showTool('tests');
|
|
if (!mark) this.start(scope, { file: path });
|
|
else this.runMark(path, mark);
|
|
return true;
|
|
}
|
|
|
|
/** a mark of the gutter run: a method, a class, a JavaScript test */
|
|
runMark(path, mark, coverage = false) {
|
|
const scope = this.scopeOf(path);
|
|
if (!scope) return;
|
|
if (mark.kind === 'class') this.start(scope, { class: mark.id, file: path }, coverage);
|
|
else this.start(scope, { test: mark.id, file: path }, coverage);
|
|
}
|
|
|
|
async start(scope, selection, coverage = false) {
|
|
if (this.run) { notify(t('Tests are already running.'), 'info'); return; }
|
|
await this.app.editors.saveAll(true);
|
|
if (scope.type === 'phpunit' || scope.type === 'pest') await this.app.docker?.();
|
|
this.lastRun = { scope: scope.id, selection, coverage };
|
|
this.open.add('scope:' + scope.id);
|
|
this.shown = null;
|
|
const label = this.describe(scope, selection);
|
|
this.run = { id: null, scope: scope.id, selection, coverage, label, started: Date.now(), count: null, done: 0, output: '' };
|
|
// what will run is marked as queued (grey), the rest keeps its last result
|
|
for (const id of this.idsOf(scope, selection)) {
|
|
for (const rid of this.byTest.get(id) || [id]) {
|
|
const r = this.results.get(rid);
|
|
if (r) this.results.set(rid, { ...r, status: 'queued' });
|
|
}
|
|
}
|
|
this.output = '';
|
|
this.task = this.app.task(t('Testing: {name}', { name: label }), { open: () => this.app.showTool('tests') });
|
|
this.render();
|
|
this.app.refreshToolHeader?.('tests');
|
|
try {
|
|
const r = await backend.invoke('tests.run', { scope: scope.id, selection, coverage });
|
|
this.run.id = r.id;
|
|
this.output = '$ ' + r.command.join(' ') + '\n';
|
|
} catch (e) {
|
|
this.run = null;
|
|
this.task?.();
|
|
notify(e.message, 'error', { title: t('The tests could not start') });
|
|
this.render();
|
|
}
|
|
}
|
|
|
|
stop() {
|
|
this.queue = [];
|
|
if (this.run?.id) backend.invoke('tests.stop', { id: this.run.id }).catch(() => null);
|
|
}
|
|
|
|
/** the tests a selection covers, by id without data set (to mark them queued) */
|
|
idsOf(scope, selection) {
|
|
const out = [];
|
|
for (const suite of scope.suites || []) {
|
|
if (selection.suite && suite.name !== selection.suite) continue;
|
|
for (const f of suite.files) {
|
|
if (selection.file && f.path !== selection.file) continue;
|
|
for (const c of f.classes || []) {
|
|
if (selection.class && c.name !== selection.class) continue;
|
|
for (const m of c.methods) if (!selection.test || selection.test === m.id) out.push(m.id);
|
|
}
|
|
for (const x of f.tests || []) if (!selection.test || selection.test === x.id) out.push(x.id);
|
|
}
|
|
}
|
|
return selection.tests ? selection.tests : out;
|
|
}
|
|
|
|
describe(scope, sel) {
|
|
if (sel.tests) return t('{n} failed tests', { n: sel.tests.length });
|
|
if (sel.test) return (sel.test.split('::').pop() || sel.test) + (sel.set ? ` ${sel.set}` : '');
|
|
if (sel.class) return sel.class.split('\\').pop();
|
|
if (sel.file) return basename(sel.file);
|
|
if (sel.suite) return sel.suite;
|
|
return scope.label;
|
|
}
|
|
|
|
progress(p) {
|
|
if (!this.run || p.id !== this.run.id) return;
|
|
if (p.count) this.run.count = (this.run.count || 0) + p.count;
|
|
for (const id of p.started || []) {
|
|
this.results.set(id, { ...(this.results.get(id) || { id, test: id.replace(/ with data set .*$/, '') }), status: 'running', scope: this.run.scope });
|
|
}
|
|
for (const r of p.results || []) this.store(r, this.run.scope);
|
|
this.run.done += (p.results || []).length;
|
|
if (p.text) this.output += p.text;
|
|
if (this.run.count) this.task?.update(null, Math.min(1, this.run.done / this.run.count));
|
|
this.redraw();
|
|
this.app.gutterRun?.rescan?.();
|
|
}
|
|
|
|
store(r, scope) {
|
|
const result = { ...r, scope };
|
|
this.results.set(r.id, result);
|
|
const list = this.byTest.get(r.test) || [];
|
|
if (!list.includes(r.id)) list.push(r.id);
|
|
this.byTest.set(r.test, list);
|
|
}
|
|
|
|
exited(p) {
|
|
if (!this.run || p.id !== this.run.id) return;
|
|
const run = this.run;
|
|
for (const r of p.results || []) this.store(r, run.scope);
|
|
// tests marked queued or running that did not report: not run this time (stopped, a fatal error)
|
|
for (const [id, r] of this.results) if (r.status === 'queued' || r.status === 'running') this.results.set(id, { ...r, status: p.code === 0 ? null : 'error', message: r.message || t('Not run: the run ended before it') });
|
|
Object.assign(this.films, p.films || {});
|
|
Object.assign(this.frames, p.frames || {});
|
|
if (p.coverage) { this.coverage = p.coverage; this.applyCoverage(); }
|
|
if (p.error) this.output += `\n${p.error}\n`;
|
|
this.output += `\n${t('Process finished with exit code {code}', { code: p.code })} (${p.seconds}s)\n`;
|
|
const c = counts(p.results || []);
|
|
this.history.unshift({ time: Date.now(), label: run.label, counts: c, seconds: p.seconds, coverage: p.coverage?.percent ?? null,
|
|
results: p.results || [], films: p.films || {}, frames: p.frames || {}, output: this.output, scope: run.scope });
|
|
this.history = this.history.slice(0, 10);
|
|
const summary = prefs.get('tests.history:' + this.app.projectKey, []);
|
|
summary.unshift({ time: Date.now(), label: run.label, counts: c, seconds: p.seconds, coverage: p.coverage?.percent ?? null });
|
|
prefs.set('tests.history:' + this.app.projectKey, summary.slice(0, 20));
|
|
this.task?.();
|
|
this.task = null;
|
|
this.run = null;
|
|
if (!(p.results || []).length && p.code !== 0) {
|
|
notify(t('The tests did not run: see the output of the run.'), 'error', { title: run.label });
|
|
this.selected = 'root';
|
|
} else if (!this.queue?.length) {
|
|
notify(t('{passed} passed, {failed} failed, {skipped} skipped', { passed: c.passed, failed: c.failed, skipped: c.skipped }), c.failed ? 'error' : 'success', { title: run.label });
|
|
}
|
|
// the first failure shown
|
|
const firstFail = (p.results || []).find((r) => r.status === 'failed' || r.status === 'error');
|
|
// the failures unfolded in the tree: their file, class, method
|
|
for (const r of (p.results || []).filter((x) => x.status === 'failed' || x.status === 'error')) {
|
|
const cls = r.test.includes('::') ? r.test.slice(0, r.test.indexOf('::')) : null;
|
|
for (const [path, entry] of this.index) {
|
|
if (entry.scope.id !== run.scope) continue;
|
|
if ((entry.file.classes || []).some((c) => c.name === cls) || (entry.file.tests || []).some((x) => x.id === r.test) || r.file === path) {
|
|
this.open.add('scope:' + entry.scope.id); this.open.add('file:' + path);
|
|
if (cls) this.open.add('class:' + cls);
|
|
if (r.set) this.open.add('test:' + r.test);
|
|
}
|
|
}
|
|
}
|
|
if (firstFail && !this.selected?.startsWith('test:')) this.selected = 'result:' + firstFail.id;
|
|
this.render();
|
|
this.app.refreshToolHeader?.('tests');
|
|
this.app.gutterRun?.rescan?.();
|
|
this.app.badge?.('tests', c.failed ? 'red' : 'on');
|
|
const next = this.queue?.shift();
|
|
if (next) this.start(...next);
|
|
}
|
|
|
|
saved(path) {
|
|
// a test file nobody knew yet (a first test): found without pressing "Find the tests again"
|
|
if (/(Test|Spec)\.php$|\.(test|spec)\.m?[jt]s$/.test(path) && !this.index.has(path)) this.discover();
|
|
if (!this.onSave || this.run || !this.lastRun) return;
|
|
if (!/\.(php|m?js|cjs|ts)$/.test(path)) return;
|
|
clearTimeout(this.saveTimer);
|
|
this.saveTimer = setTimeout(() => {
|
|
const scope = this.scopes.find((s) => s.id === this.lastRun.scope);
|
|
if (scope && !this.run) this.start(scope, this.lastRun.selection, this.lastRun.coverage);
|
|
}, 400);
|
|
}
|
|
|
|
// statuses -----------------------------------------------------------------------------------------------
|
|
|
|
statusOf(kind, id) {
|
|
if (kind === 'test') return worst((this.byTest.get(id) || [id]).map((rid) => this.results.get(rid)?.status));
|
|
if (kind === 'class') return worst([...this.byTest.keys()].filter((k) => k.startsWith(id + '::')).flatMap((k) => this.byTest.get(k).map((rid) => this.results.get(rid)?.status)));
|
|
return null;
|
|
}
|
|
|
|
testsOfFile(f) {
|
|
return [...(f.classes || []).flatMap((c) => c.methods.map((m) => m.id)), ...(f.tests || []).map((x) => x.id)];
|
|
}
|
|
|
|
// drawing ------------------------------------------------------------------------------------------------
|
|
|
|
render() {
|
|
clear(this.node);
|
|
const state = this.shown !== null ? this.history[this.shown] : null;
|
|
this.node.append(this.summaryBar(state), this.toolbar());
|
|
const tree = el('div.tests-tree.tree', { tabIndex: 0 });
|
|
const detail = el('div.tests-detail');
|
|
this.node.append(el('div.tests-split', {}, tree, detail));
|
|
if (this.error) tree.append(el('div.placeholder', {}, this.error));
|
|
else if (!this.scopes.length) tree.append(el('div.placeholder', {}, t('No tests found: PHPUnit (phpunit.xml, tests/*Test.php), Pest, game tests, *.test.mjs.')));
|
|
this.rows = [];
|
|
for (const scope of this.scopes) this.drawScope(tree, scope);
|
|
if (this.coverage) this.drawCoverageRow(tree);
|
|
this.detail(detail);
|
|
requestAnimationFrame(() => tree.querySelector('.row.sel')?.scrollIntoView({ block: 'nearest' }));
|
|
}
|
|
|
|
summaryBar(state) {
|
|
const results = state ? state.results : [...this.results.values()].filter((r) => r.status);
|
|
const c = counts(results);
|
|
const bar = el('div.tests-bar');
|
|
const part = (n, cls) => (n ? el(`span.${cls}`, { style: { flexGrow: String(n) } }) : null);
|
|
bar.append(...[part(c.passed, 'pass'), part(c.failed, 'fail'), part(c.skipped, 'skip'), part(c.running, 'run')].filter(Boolean));
|
|
if (!c.total) bar.append(el('span.none', { style: { flexGrow: '1' } }));
|
|
const running = this.run ? el('span.tests-running', {}, el('span.spinner'), ` ${this.run.label} ${this.run.count ? `${this.run.done}/${this.run.count}` : ''}`) : null;
|
|
const history = el('div.tests-history', { title: t('The last runs') });
|
|
for (const [i, h] of this.history.slice(0, 10).reverse().entries()) {
|
|
const index = Math.min(this.history.length, 10) - 1 - i;
|
|
const total = h.counts.total || 1;
|
|
history.append(el(`span.h${this.shown === index ? '.on' : ''}`, { title: `${h.label}: ${h.counts.passed} ✔ ${h.counts.failed} ✘ ${h.counts.skipped} ↩ — ${h.seconds}s`,
|
|
onclick: () => { this.shown = this.shown === index ? null : index; this.render(); } },
|
|
el('i.f', { style: { height: `${Math.round(100 * h.counts.failed / total)}%` } }), el('i.p', { style: { height: `${Math.round(100 * h.counts.passed / total)}%` } })));
|
|
}
|
|
return el('div.tests-summary', {},
|
|
el('span.pass', {}, `✔ ${c.passed}`), el('span.fail', {}, `✘ ${c.failed}`), el('span.skip', {}, `↩ ${c.skipped}`),
|
|
el('span.dim', {}, duration(c.ms)),
|
|
this.coverage ? el('span.cov', { title: t('Code coverage of the last run with coverage') }, `${t('Coverage')} ${this.coverage.percent ?? 0}%`) : null,
|
|
state ? el('span.dim', {}, t('Run of {time}', { time: new Date(state.time).toLocaleTimeString() })) : null,
|
|
running, el('span.grow'), history, bar);
|
|
}
|
|
|
|
toolbar() {
|
|
const f = (value, label) => el(`button.chip${this.filter === value ? '.on' : ''}`, { onclick: () => { this.filter = value; prefs.set('tests.filter', value); this.render(); } }, label);
|
|
return el('div.tests-filters', {}, f('all', t('All')), f('failed', t('Failed')), f('slow', t('Slow (≥ {ms} ms)', { ms: SLOW_MS })),
|
|
this.coverage ? el(`button.chip${this.showCoverage ? '.on' : ''}`, { onclick: () => { this.showCoverage = !this.showCoverage; this.applyCoverage(); this.render(); } }, t('Coverage in the editor')) : null);
|
|
}
|
|
|
|
visible(ids) {
|
|
if (this.filter === 'all') return true;
|
|
const res = ids.flatMap((id) => (this.byTest.get(id) || [id]).map((rid) => this.results.get(rid)).filter(Boolean));
|
|
if (this.filter === 'failed') return res.some((r) => r.status === 'failed' || r.status === 'error');
|
|
return res.some((r) => (r.duration || 0) >= SLOW_MS);
|
|
}
|
|
|
|
row(tree, key, depth, { label, hint, status, hasKids, onRun, onOpen, menuItems, titleText, game }) {
|
|
const open = this.open.has(key) || this.filter !== 'all';
|
|
const twisty = el(`span.twisty${hasKids ? '' : '.leaf'}`, { onclick: (e) => { e.stopPropagation(); this.toggle(key); } });
|
|
const st = el(`span.st.${status || 'none'}`, {}, status ? STATUS_ICON[status] : '○');
|
|
const r = el(`div.row${hasKids && open ? '.open' : ''}${this.selected === key ? '.sel' : ''}`, {
|
|
style: { paddingLeft: `${6 + depth * 16}px` }, title: titleText || '',
|
|
onclick: () => { this.selected = key; this.render(); },
|
|
ondblclick: () => (onOpen ? onOpen() : this.toggle(key)),
|
|
oncontextmenu: (e) => { e.preventDefault(); menu([...(onRun ? [{ label: t('Run'), icon: 'play', action: () => onRun(false) }] : []), ...(menuItems || []), ...(onOpen ? [{ label: t('Open'), action: onOpen }] : [])], { x: e.clientX, y: e.clientY }); },
|
|
}, twisty, st, game ? el('span.game', { title: t('Game test: its frames are filmed') }, icon('game')) : null, el('span.label', {}, label), hint ? el('span.hint', {}, hint) : null,
|
|
onRun ? el('span.run', { title: t('Run'), onclick: (e) => { e.stopPropagation(); onRun(false); } }, '▶') : null);
|
|
tree.append(r);
|
|
return open;
|
|
}
|
|
|
|
toggle(key) {
|
|
if (this.open.has(key)) this.open.delete(key); else this.open.add(key);
|
|
prefs.set('tests.open', [...this.open].slice(-300));
|
|
this.render();
|
|
}
|
|
|
|
drawScope(tree, scope) {
|
|
const all = scope.suites.flatMap((s) => s.files.flatMap((f) => this.testsOfFile(f)));
|
|
const key = 'scope:' + scope.id;
|
|
if (!this.open.has('init:' + scope.id)) { this.open.add('init:' + scope.id); if (this.scopes.length <= 3) this.open.add(key); }
|
|
const kinds = { phpunit: 'PHPUnit', pest: 'Pest', node: 'node --test', vitest: 'Vitest', jest: 'Jest' };
|
|
const open = this.row(tree, key, 0, { label: scope.label, hint: `${kinds[scope.type] || scope.type} · ${all.length}`, status: worst(all.map((id) => this.statusOf('test', id))), hasKids: true,
|
|
onRun: () => this.start(scope, {}), menuItems: this.coverable(scope) ? [{ label: t('Run with coverage'), icon: 'check', action: () => this.start(scope, {}, true) }] : [] });
|
|
if (!open) return;
|
|
const named = scope.suites.length > 1;
|
|
for (const suite of scope.suites) {
|
|
let depth = 1;
|
|
if (named) {
|
|
const ids = suite.files.flatMap((f) => this.testsOfFile(f));
|
|
if (!this.visible(ids)) continue;
|
|
const sk = `suite:${scope.id}:${suite.name}`;
|
|
if (!this.row(tree, sk, 1, { label: suite.name, hint: String(ids.length), status: worst(ids.map((id) => this.statusOf('test', id))), hasKids: true, onRun: () => this.start(scope, { suite: suite.name }) })) continue;
|
|
depth = 2;
|
|
}
|
|
for (const f of suite.files) this.drawFile(tree, scope, f, depth);
|
|
}
|
|
}
|
|
|
|
drawFile(tree, scope, f, depth) {
|
|
const ids = this.testsOfFile(f);
|
|
if (!this.visible(ids)) return;
|
|
const key = 'file:' + f.path;
|
|
const open = this.row(tree, key, depth, { label: basename(f.path), hint: f.path.replace(/\/[^/]*$/, ''), status: worst(ids.map((id) => this.statusOf('test', id))), hasKids: true,
|
|
onRun: (cov) => this.start(scope, { file: f.path }, cov), onOpen: () => this.app.editors.open(f.path),
|
|
menuItems: this.coverable(scope) ? [{ label: t('Run with coverage'), icon: 'check', action: () => this.start(scope, { file: f.path }, true) }] : [] });
|
|
if (!open) return;
|
|
for (const c of f.classes || []) {
|
|
const cids = c.methods.map((m) => m.id);
|
|
if (!this.visible(cids)) continue;
|
|
const ck = 'class:' + c.name;
|
|
const copen = (f.classes.length === 1 && !this.open.has('closed:' + ck)) || this.open.has(ck);
|
|
if (f.classes.length === 1 && !this.open.has(ck) && !this.open.has('closed:' + ck)) this.open.add(ck);
|
|
if (!this.row(tree, ck, depth + 1, { label: c.short, hint: c.name.includes('\\') ? c.name.slice(0, c.name.lastIndexOf('\\')) : '', status: this.statusOf('class', c.name), hasKids: true, game: c.game,
|
|
onRun: () => this.start(scope, { class: c.name, file: f.path }), onOpen: () => this.app.editors.open(f.path, { line: c.line }),
|
|
menuItems: this.coverable(scope) ? [{ label: t('Run with coverage'), icon: 'check', action: () => this.start(scope, { class: c.name, file: f.path }, true) }] : [] }) && !copen) continue;
|
|
for (const m of c.methods) this.drawTest(tree, scope, f, m, depth + 2, c.game);
|
|
}
|
|
for (const x of f.tests || []) this.drawTest(tree, scope, f, { id: x.id, name: x.name, line: x.line }, depth + 1, false);
|
|
}
|
|
|
|
drawTest(tree, scope, f, m, depth, game) {
|
|
if (!this.visible([m.id])) return;
|
|
const sets = (this.byTest.get(m.id) || []).filter((rid) => rid !== m.id);
|
|
const key = 'test:' + m.id;
|
|
const r = this.results.get(m.id);
|
|
const time = sets.length ? sets.reduce((n, rid) => n + (this.results.get(rid)?.duration || 0), 0) : r?.duration;
|
|
const open = this.row(tree, key, depth, { label: m.name, hint: [m.provider ? `⟵ ${m.provider}()` : '', time !== undefined && time !== null && (r || sets.length) ? duration(time) : ''].filter(Boolean).join(' '),
|
|
status: this.statusOf('test', m.id), hasKids: sets.length > 0, game,
|
|
onRun: (cov) => this.start(scope, { test: m.id, file: f.path }, cov), onOpen: () => this.app.editors.open(f.path, { line: m.line }),
|
|
menuItems: this.coverable(scope) ? [{ label: t('Run with coverage'), icon: 'check', action: () => this.start(scope, { test: m.id, file: f.path }, true) }] : [] });
|
|
if (!open) return;
|
|
for (const rid of sets) {
|
|
const s = this.results.get(rid);
|
|
if (!s || (this.filter === 'failed' && !['failed', 'error'].includes(s.status)) || (this.filter === 'slow' && (s.duration || 0) < SLOW_MS)) continue;
|
|
this.row(tree, 'result:' + rid, depth + 1, { label: s.set || rid, hint: duration(s.duration), status: s.status, hasKids: false,
|
|
onRun: () => this.start(scope, { test: m.id, set: s.set, file: f.path }), onOpen: () => this.app.editors.open(f.path, { line: m.line }) });
|
|
}
|
|
}
|
|
|
|
drawCoverageRow(tree) {
|
|
const files = Object.entries(this.coverage.files || {});
|
|
const key = 'coverage';
|
|
const open = this.row(tree, key, 0, { label: t('Coverage'), hint: `${this.coverage.percent ?? 0}% · ${t('{n} files', { n: files.length })}`, hasKids: true });
|
|
if (!open) return;
|
|
for (const [path, f] of files.sort((a, b) => a[1].percent - b[1].percent)) {
|
|
const r = el(`div.row.cov-row${this.selected === 'cov:' + path ? '.sel' : ''}`, { style: { paddingLeft: '22px' }, title: path, onclick: () => { this.app.editors.open(path); } },
|
|
el('span.twisty.leaf'), el('span.covbar', {}, el('i', { style: { width: `${f.percent}%` } })), el('span.label', {}, basename(path)), el('span.hint', {}, `${f.percent}% ${path.replace(/\/[^/]*$/, '')}`));
|
|
tree.append(r);
|
|
}
|
|
}
|
|
|
|
// the detail pane ----------------------------------------------------------------------------------------
|
|
|
|
findResult(key) {
|
|
if (!key) return null;
|
|
if (key.startsWith('result:')) return this.resultById(key.slice(7));
|
|
if (key.startsWith('test:')) {
|
|
const id = key.slice(5);
|
|
const sets = this.byTest.get(id) || [id];
|
|
return sets.map((rid) => this.resultById(rid)).filter(Boolean).sort((a, b) => ['error', 'failed'].indexOf(b.status) - ['error', 'failed'].indexOf(a.status))[0] || { id, test: id, status: null };
|
|
}
|
|
return null;
|
|
}
|
|
|
|
resultById(id) {
|
|
if (this.shown !== null) return this.history[this.shown]?.results.find((r) => r.id === id) || null;
|
|
return this.results.get(id) || null;
|
|
}
|
|
|
|
detail(box) {
|
|
const r = this.findResult(this.selected);
|
|
if (!r) {
|
|
const state = this.shown !== null ? this.history[this.shown] : null;
|
|
const failures = (state ? state.results : [...this.results.values()]).filter((x) => x.status === 'failed' || x.status === 'error');
|
|
if (failures.length) {
|
|
box.append(el('div.tests-h', {}, t('Failures ({n})', { n: failures.length })));
|
|
for (const f of failures.slice(0, 50)) box.append(el('div.tests-fail-row', { onclick: () => { this.selected = 'result:' + f.id; this.render(); } }, el('span.st.failed', {}, '✘'), ` ${f.id}`, el('div.msg', {}, f.message || '')));
|
|
}
|
|
const output = state ? state.output : this.output;
|
|
if (output) {
|
|
box.append(el('div.tests-h', {}, t('Output')));
|
|
const pre = el('div.console.tests-console');
|
|
pre.innerHTML = this.app.runner.format(output);
|
|
this.app.runner.bindLinks(pre);
|
|
box.append(pre);
|
|
}
|
|
if (!failures.length && !output) box.append(el('div.placeholder', {}, t('Select a test to see its result. Run tests with ▶ (the tree, the gutter of the editor, Ctrl+Shift+F10 at the cursor).')));
|
|
return;
|
|
}
|
|
const status = r.status || 'none';
|
|
box.append(el('div.tests-h', {}, el(`span.st.${status}`, {}, STATUS_ICON[r.status] || '○'), ` ${r.id}`, r.duration !== undefined && r.status ? el('span.dim', {}, ` ${duration(r.duration)}`) : null));
|
|
if (!r.status) box.append(el('div.placeholder.small', {}, t('Not run yet.')));
|
|
if (r.message) box.append(el('div.tests-message', {}, r.message));
|
|
if (r.expected !== undefined || r.actual !== undefined) box.append(this.diffView(r.expected, r.actual));
|
|
if (r.details) box.append(el('div.tests-h2', {}, t('Stack')), this.stack(r.details));
|
|
if (r.output) box.append(el('div.tests-h2', {}, t('Printed output')), el('pre.tests-out', {}, r.output));
|
|
const films = this.shown !== null ? this.history[this.shown].films : this.films;
|
|
const frames = this.shown !== null ? this.history[this.shown].frames : this.frames;
|
|
const film = films[r.test] || films[r.id];
|
|
const last = frames[r.test] || frames[r.id];
|
|
if (film?.length || last) box.append(this.filmView(film || [], last));
|
|
}
|
|
|
|
diffView(expected, actual) {
|
|
const rows = sideBySide(expected, actual);
|
|
const table = el('div.tests-diff');
|
|
table.append(el('div.dh', {}, t('Expected')), el('div.dh', {}, t('Actual')));
|
|
for (const row of rows) {
|
|
table.append(el(`div.dl.${row.kind}`, {}, row.left ?? ''), el(`div.dr.${row.kind}`, {}, row.right ?? ''));
|
|
}
|
|
return el('div', {}, el('div.tests-h2', {}, t('Difference')), table);
|
|
}
|
|
|
|
stack(text) {
|
|
const box = el('pre.tests-stack');
|
|
let at = 0;
|
|
for (const loc of locations(text)) {
|
|
box.append(text.slice(at, loc.index));
|
|
const path = this.projectPath(loc.path);
|
|
box.append(path ? el('a.loc', { onclick: () => this.app.editors.open(path, { line: loc.line }) }, loc.text) : loc.text);
|
|
at = loc.index + loc.text.length;
|
|
}
|
|
box.append(text.slice(at));
|
|
return box;
|
|
}
|
|
|
|
projectPath(path) {
|
|
const known = this.app.tree?.files || [];
|
|
const p = path.replace(/^\/(workspace|app|w)\//, '');
|
|
if (known.includes(p)) return p;
|
|
return known.find((f) => f.endsWith('/' + p) || p.endsWith('/' + f)) || (p.startsWith('/') ? null : p);
|
|
}
|
|
|
|
filmView(film, last) {
|
|
const box = el('div.tests-film');
|
|
const img = el('img.tests-frame', { alt: '' });
|
|
const pictures = [...film];
|
|
if (last && !pictures.includes(last)) pictures.push(last);
|
|
const label = el('span.dim');
|
|
const slider = el('input', { type: 'range', min: 0, max: Math.max(0, pictures.length - 1), value: Math.max(0, pictures.length - 1) });
|
|
const cache = new Map();
|
|
const show = async (i) => {
|
|
const path = pictures[i];
|
|
if (!path) return;
|
|
label.textContent = `${i + 1} / ${pictures.length}`;
|
|
if (!cache.has(path)) {
|
|
try {
|
|
const r = await backend.invoke('file.bytes', { path, offset: 0, length: 8 * 1024 * 1024 });
|
|
cache.set(path, 'data:image/png;base64,' + r.base64);
|
|
} catch { cache.set(path, ''); }
|
|
}
|
|
if (+slider.value === i) img.src = cache.get(path);
|
|
};
|
|
let timer = null;
|
|
const play = el('button', { title: t('Play the frames'), onclick: () => {
|
|
if (timer) { clearInterval(timer); timer = null; return; }
|
|
let i = 0;
|
|
timer = setInterval(() => { if (!box.isConnected || i >= pictures.length) { clearInterval(timer); timer = null; return; } slider.value = i; show(i++); }, 80);
|
|
} }, icon('play'));
|
|
slider.addEventListener('input', () => show(+slider.value));
|
|
box.append(el('div.tests-h2', {}, t('Frames of the game test')), el('div.tests-film-bar', {}, play, slider, label,
|
|
last ? el('button', { title: t('Open the last frame'), onclick: () => this.app.editors.open(last) }, icon('camera')) : null), img);
|
|
show(pictures.length - 1);
|
|
return box;
|
|
}
|
|
|
|
// coverage in the editor ---------------------------------------------------------------------------------
|
|
|
|
attach(editor) {
|
|
if (editor.__testsCoverage) return;
|
|
editor.__testsCoverage = true;
|
|
editor.onDidChangeModel(() => this.decorate(editor.getModel()));
|
|
this.decorate(editor.getModel());
|
|
}
|
|
|
|
applyCoverage() {
|
|
for (const group of this.app.editors.groups) this.decorate(group.editor.getModel());
|
|
for (const editor of monaco.editor.getEditors?.() || []) this.decorate(editor.getModel());
|
|
}
|
|
|
|
decorate(model) {
|
|
if (!model || model.isDisposed()) return;
|
|
const key = model.uri.toString();
|
|
const file = this.showCoverage ? this.coverage?.files?.[pathOf(model.uri)] : null;
|
|
const decorations = [];
|
|
if (file) {
|
|
const add = (line, cls, hover) => decorations.push({ range: new monaco.Range(line, 1, line, 1), options: { isWholeLine: true, linesDecorationsClassName: cls,
|
|
overviewRuler: { color: cls === 'cov-hit' ? 'rgba(95,183,96,.6)' : 'rgba(224,90,90,.7)', position: monaco.editor.OverviewRulerLane.Left }, hoverMessage: { value: hover } } });
|
|
for (const l of file.covered) add(l, 'cov-hit', t('Covered by the tests'));
|
|
for (const l of file.uncovered) add(l, 'cov-miss', t('Not covered by the tests'));
|
|
}
|
|
this.coverageDecorations.set(key, model.deltaDecorations(this.coverageDecorations.get(key) || [], decorations));
|
|
}
|
|
}
|