rob-revisited/ide/ui/js/test-wizard.js

247 lines
14 KiB
JavaScript

// The test wizard: PHPUnit tests made from a form. The kind (unit test of a class with its dependencies mocked, a service of the container,
// a functional test of a route with a login when it is protected, an API Platform operation, a browser test with Panther), the class or
// the routes picked, the assertions chosen from a palette, the file placed by autoload-dev (tests/...), the code shown as a diff before it is
// written; a method can be added to a test class that already exists, and the result is run by the Tests window. PHP side: ide/src/TestWizard.
// The model's flows are in test-wizard-model.js (tested without a DOM).
import { backend } from './backend.js';
import { el, clear, icon, dialog, notify, t, debounce } from './ui.js';
import { diffPane, writeChanges, installNotice } from './wizard-preview.js';
import { KINDS, KIND_LABELS, kindsFor, paletteFor, assertionCode, newAssertion, newTest, cleanModel, defaultLogin, filterRoutes, short } from './test-wizard-model.js';
function select(options, value, onchange, cls = '') {
return el('select.input' + cls, { onchange: (e) => onchange(e.target.value) }, ...options.map(([v, text]) => el('option', { value: v, selected: String(value ?? '') === String(v) }, text)));
}
class TestWizard {
constructor(app, info, { kind = 'unit', target = '', file = null } = {}) {
this.app = app;
this.info = info;
this.state = { kind, target, class: '', tests: [], login: defaultLogin(info) };
this.classes = null;
this.routes = null;
this.classInfo = null;
this.query = '';
this.existing = file;
this.refresh = debounce(() => this.preview(), 250);
}
async open() {
this.top = el('div.wg-top');
this.pick = el('div.wg-pick');
this.list = el('div.wg-tests');
this.pane = diffPane();
this.status = el('div.wg-status');
this.dialog = dialog({
title: t('New test'), wide: true, sticky: true,
body: el('div.wg', {}, el('div.wg-left', {}, this.top, this.pick, this.list), el('div.wg-right', {}, el('div.wg-right-head', {}, icon('diff'), el('span', {}, t('The test file'))), this.pane.node, this.status)),
buttons: [
{ label: t('Close') },
{ label: t('Write the file'), tour: 'testwizard-write', action: () => this.write(false) },
{ label: t('Write and run'), primary: true, tour: 'testwizard-run', action: () => this.write(true) },
],
onClose: () => this.pane.dispose(),
});
this.dialog.box.classList.add('wg-dialog');
this.render();
await this.loadTargets();
return this;
}
get kind() { return this.state.kind; }
async loadTargets() {
try {
if (['unit', 'kernel'].includes(this.kind) && !this.classes) this.classes = (await backend.invoke('testwizard.classes', {})).classes;
if (['functional', 'panther'].includes(this.kind) && !this.routes) this.routes = await backend.invoke('testwizard.routes', {});
if (this.kind === 'api' && !this.apiRoutes) this.apiRoutes = await backend.invoke('testwizard.routes', {});
if (this.state.target && !this.classInfo) await this.pickClass(this.state.target);
} catch (e) { notify(e.message || String(e), 'error', { title: t('Tests') }); }
this.render();
}
setKind(kind) {
Object.assign(this.state, { kind, tests: [], target: '', class: '' });
this.classInfo = null;
this.loadTargets();
}
render() {
this.renderTop();
this.renderPick();
this.renderTests();
this.preview();
}
renderTop() {
clear(this.top);
const plan = this.info.kinds[this.kind];
if (plan && !plan.ready) {
this.top.append(installNotice(this.app, t('This kind of test needs these packages'), plan.missing, async () => { this.info = await backend.invoke('testwizard.info', {}); this.render(); }));
}
this.top.append(el('div.wg-kinds', {}, ...kindsFor(this.info).map((k) => el('button.wg-kind' + (k === this.kind ? '.on' : ''), { onclick: () => this.setKind(k) }, t(KIND_LABELS[k])))));
const existing = this.info.tests || [];
this.top.append(el('div.wg-row', {},
el('label.wg-field', {}, el('span', {}, t('Test class')), el('input.input.wg-w', { value: this.state.class, spellcheck: false, placeholder: 'App\\Tests\\FooTest', oninput: (e) => { this.state.class = e.target.value; this.refresh(); } })),
existing.length ? el('label.wg-field', {}, el('span', {}, t('Add to an existing test class')), select([['', '—'], ...existing.map((f) => [f.class, f.class])], '', (v) => { if (v) { this.state.class = v; this.render(); } })) : null));
}
renderPick() {
clear(this.pick);
const search = el('input.input', { placeholder: t('Filter…'), value: this.query, spellcheck: false, oninput: (e) => { this.query = e.target.value; this.renderPickList(); } });
this.pickList = el('div.wg-pick-list');
const label = { unit: t('Class to test'), kernel: t('Service to test'), functional: t('Routes to test'), panther: t('Pages to test'), api: t('Operations to test') }[this.kind];
this.pick.append(el('div.wg-pick-head', {}, el('strong', {}, label), search), this.pickList);
this.renderPickList();
}
renderPickList() {
clear(this.pickList);
const q = this.query.trim().toLowerCase();
if (['unit', 'kernel'].includes(this.kind)) {
if (!this.classes) { this.pickList.append(el('div.pub-faint', {}, t('Loading…'))); return; }
const list = this.classes.filter((c) => c.kind !== 'entity' && (!q || c.class.toLowerCase().includes(q))).slice(0, 80);
for (const c of list) this.pickList.append(el('button.wg-item' + (c.class === this.state.target ? '.on' : ''), { onclick: () => this.pickClass(c.class) }, el('span', {}, short(c.class)), el('small', {}, c.class)));
if (this.classInfo) this.pickList.append(this.methodsList());
return;
}
const data = this.kind === 'api' ? this.apiRoutes : this.routes;
if (!data) { this.pickList.append(el('div.pub-faint', {}, t('Loading…'))); return; }
if (!data.ok) { this.pickList.append(el('div.wg-error', {}, t('The routes could not be read: {output}', { output: String(data.output || '').slice(0, 300) }))); return; }
for (const r of filterRoutes(data.routes, q, { api: this.kind === 'api' }).slice(0, 120)) {
const on = this.state.tests.some((x) => (x.route?.name || x.operation?.path + x.operation?.method) === (this.kind === 'api' ? r.path + r.method : r.name));
this.pickList.append(el('button.wg-item' + (on ? '.on' : ''), { onclick: () => this.toggleRoute(r) },
el('span', {}, `${r.method} ${r.path}`), el('small', {}, r.name + (r.protected ? ` 🔒 ${t('protected')}` : ''))));
}
}
/** the public methods of the class under test: a test each */
methodsList() {
return el('div.wg-methods', {}, el('strong', {}, t('Methods')), ...this.classInfo.methods.map((m) => el('label.wg-check', {},
el('input', { type: 'checkbox', checked: this.state.tests.some((x) => x.method === m.name), onchange: (e) => this.toggleMethod(m, e.target.checked) }),
el('span', {}, `${m.name}(${m.params.map((p) => `${p.type ? short(p.type) + ' ' : ''}$${p.name}`).join(', ')})${m.return ? ': ' + short(m.return) : ''}`))));
}
async pickClass(cls) {
try {
this.classInfo = await backend.invoke('testwizard.class', { class: cls });
this.state.target = cls;
this.state.tests = [];
if (!this.existing || !this.state.class) this.state.class = this.classInfo.testClass;
this.render();
} catch (e) { notify(e.message || String(e), 'error', { title: t('Tests') }); }
}
toggleMethod(m, on) {
if (!on) this.state.tests = this.state.tests.filter((x) => x.method !== m.name);
else this.state.tests.push(newTest(this.kind, { method: m.name, returnsVoid: m.return === 'void' }, this.info));
this.renderTests();
this.refresh();
}
toggleRoute(r) {
const key = (x) => (this.kind === 'api' ? x.operation?.path + x.operation?.method : x.route?.name);
const want = this.kind === 'api' ? r.path + r.method : r.name;
if (this.state.tests.some((x) => key(x) === want)) this.state.tests = this.state.tests.filter((x) => key(x) !== want);
else {
this.state.tests.push(newTest(this.kind, this.kind === 'api' ? { operation: { method: r.method, path: r.path.replace(/\{[^}]+\}/g, '1').replace('.{_format}', '') } } : { route: r }, this.info));
if (!this.state.class && r.class) this.state.class = this.suggestClass(r);
}
this.renderPickList();
this.renderTests();
this.refresh();
}
suggestClass(r) {
const dev = this.info.dev.prefix;
const base = r.class ? r.class.replace(/^.*?\\Controller\\/, 'Controller\\') : `Controller\\${short(r.name)}Controller`;
return `${dev}${base}Test`;
}
renderTests() {
clear(this.list);
const protectedOnes = this.state.tests.some((x) => x.protected);
if (protectedOnes) this.list.append(this.loginBox());
for (const test of this.state.tests) this.list.append(this.testRow(test));
if (!this.state.tests.length) this.list.append(el('div.pub-faint', {}, t('Tick what to test: a test is made for each.')));
}
loginBox() {
const l = this.state.login;
const on = () => this.refresh();
return el('div.wg-login', {}, el('strong', {}, t('Log in for the protected routes')),
select([['memory', t('an in-memory user')], ['entity', t('a user of the database')]], l.mode, (v) => { l.mode = v; this.renderTests(); on(); }),
l.mode === 'entity'
? el('span', {}, el('input.input', { value: l.userClass, placeholder: 'App\\Entity\\User', oninput: (e) => { l.userClass = e.target.value; on(); } }),
el('input.input.wg-s', { value: l.property, oninput: (e) => { l.property = e.target.value; on(); } }), el('input.input', { value: l.value, oninput: (e) => { l.value = e.target.value; on(); } }))
: el('span', {}, el('input.input.wg-s', { value: l.identifier, oninput: (e) => { l.identifier = e.target.value; on(); } }),
el('input.input', { value: l.roles.join(', '), placeholder: 'ROLE_ADMIN', oninput: (e) => { l.roles = e.target.value.split(/[,\s]+/).filter(Boolean); on(); } })));
}
testRow(test) {
const palette = paletteFor(this.kind, this.info);
const asserts = test.asserts.map((a, i) => {
const spec = this.info.assertions.find((x) => x.id === a.id);
const codeEl = el('code.wg-assert-code', {}, assertionCode(a, this.info));
return el('div.wg-assert', {}, el('span.wg-assert-label', {}, t(spec.label)),
...spec.args.map((arg, k) => el('input.input', { value: a.args[k] ?? arg.default, title: arg.name, spellcheck: false, oninput: (e) => { a.args[k] = e.target.value; codeEl.textContent = assertionCode(a, this.info); this.refresh(); } })),
codeEl, el('button.cwz-del', { title: t('Remove'), onclick: () => { test.asserts.splice(i, 1); this.renderTests(); this.refresh(); } }, icon('trash')));
});
const add = select([['', t('+ Add an assertion…')], ...palette.map((p) => [p.id, t(p.label)])], '', (v) => { if (v) { test.asserts.push(newAssertion(v, this.info)); this.renderTests(); this.refresh(); } }, '.wg-add');
const what = test.method ? `${short(this.state.target)}::${test.method}()` : (test.route ? `${test.route.method} ${test.route.path}` : `${test.operation?.method} ${test.operation?.path}`);
return el('div.wg-test', {}, el('div.wg-test-head', {}, el('input.input.wg-w', { value: test.name, spellcheck: false, oninput: (e) => { test.name = e.target.value; this.refresh(); } }), el('small', {}, what),
test.method ? el('label.wg-check', { title: t('The test takes its data from a data provider') }, el('input', { type: 'checkbox', checked: !!test.provider, onchange: (e) => { test.provider = e.target.checked; this.refresh(); } }), el('span', {}, t('data provider'))) : null),
...asserts, add);
}
async preview() {
const model = cleanModel(this.state);
clear(this.status);
if (!model.tests.length || !model.class) { this.changes = null; this.pane.show([]); this.status.append(el('div.pub-faint', {}, t('Choose what to test and the test class.'))); return; }
try {
const r = await backend.invoke('testwizard.preview', { model });
this.changes = r.changes;
this.pane.show(r.changes);
this.status.append(el('div.pub-faint', {}, r.changes[0].before === null ? t('A new file: {file}', { file: r.file }) : t('{n} test(s) added to {file}', { n: model.tests.length, file: r.file })));
} catch (e) {
this.changes = null;
this.pane.show([], String(e.message || e));
}
}
async write(run) {
await this.preview();
if (!this.changes) return false;
const files = await writeChanges(this.app, this.changes);
if (!files.length) return false;
const file = files[0];
notify(t('Written: {files}', { files: file }), 'success', { title: t('Tests') });
this.app.editors?.open?.(file);
if (run) await runTestFile(this.app, file);
return true;
}
}
/** shows the Tests window and runs one test file in it */
export async function runTestFile(app, file) {
if (!app.tests) return;
app.showTool('tests', true);
await app.tests.discover?.();
const scope = app.tests.scopeOf?.(file);
if (scope) await app.tests.start(scope, { file });
else notify(t('This file is not in a test suite the Tests window knows (phpunit.xml?).'), 'warning', { title: t('Tests') });
}
/** The test wizard: a new test; `target` = a class to test (unit), `file` = an existing test class to add to. */
export async function openTestWizard(app, { kind = 'unit', target = '', file = null } = {}) {
try {
const info = await backend.invoke('testwizard.info', {});
const w = new TestWizard(app, info, { kind, target, file });
if (file) w.state.class = info.tests.find((x) => x.file === file)?.class || '';
return await w.open();
} catch (e) {
notify(e.message || String(e), 'error', { title: t('Tests') });
return null;
}
}
export { KINDS };