rob-revisited/ide/ui/js/fixtures.test.mjs

153 lines
10 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The fixtures model, the test wizard's model and the install flow (no DOM, a fake runner). Run: node --test ide/ui/js/fixtures.test.mjs
import test from 'node:test';
import assert from 'node:assert/strict';
import { typesFor, defaultGenerator, sample, sampleRows, newModel, cleanModel, coerce, dependencies, loadLine, TYPES, TYPE_LABELS } from './fixtures-model.js';
import { kindsFor, paletteFor, assertionCode, newAssertion, testName, newTest, cleanModel as cleanTest, defaultLogin, filterRoutes, KINDS, KIND_LABELS } from './test-wizard-model.js';
import { installPackages } from './wizard-install.js';
const info = {
catalog: [
{ name: 'sentence', group: 'Text', args: [{ name: 'nbWords', default: 6 }], types: ['string'], samples: ['Quia est sit.', 'Eos qui amet.'] },
{ name: 'email', group: 'People', args: [], types: ['string'], samples: ['[email protected]'] },
],
enums: { 'App\\Enum\\Status': [{ name: 'Draft', value: 'draft' }, { name: 'Published', value: 'published' }] },
fixtures: [{ class: 'App\\DataFixtures\\UserFixtures', entity: 'App\\Entity\\User', generated: true }],
kind: 'faker', rootNamespace: 'App',
entities: [{ class: 'App\\Entity\\Post', name: 'Post', fields: [
{ name: 'title', type: 'string', suggest: { type: 'faker', formatter: 'sentence', args: [4] } },
{ name: 'status', type: 'string', enumType: 'App\\Enum\\Status', suggest: { type: 'enum', class: 'App\\Enum\\Status', mode: 'random' } },
{ name: 'author', type: 'ManyToOne', relation: true, target: 'App\\Entity\\User', suggest: { type: 'ref', target: 'App\\Entity\\User', mode: 'random' } },
{ name: 'tags', type: 'ManyToMany', relation: true, target: 'App\\Entity\\Tag', suggest: { type: 'refs', target: 'App\\Entity\\Tag', min: 1, max: 3 } },
] }],
};
test('a field takes the generators that fit it', () => {
assert.deepEqual(typesFor({ relation: true, type: 'ManyToMany' }), ['refs', 'null', 'skip']);
assert.deepEqual(typesFor({ relation: true, type: 'ManyToOne' }), ['ref', 'null', 'skip']);
assert.ok(typesFor({ enumType: 'App\\Enum\\Status', type: 'string' }).includes('enum'));
assert.equal(typesFor({ type: 'integer' })[0], 'between');
assert.equal(typesFor({ type: 'datetime_immutable' })[0], 'dateBetween');
for (const ty of TYPES) assert.ok(TYPE_LABELS[ty], ty);
});
test('switching the generator gives sensible parameters', () => {
assert.deepEqual(defaultGenerator('faker', { type: 'string' }, info), { type: 'faker', formatter: 'sentence', args: [6] });
assert.deepEqual(defaultGenerator('between', { type: 'decimal' }, info), { type: 'between', min: 1, max: 100, float: true, decimals: 2, cast: 'string' });
assert.equal(defaultGenerator('dateBetween', { type: 'date', immutable: true }, info).immutable, true);
assert.deepEqual(defaultGenerator('ref', { target: 'App\\Entity\\User' }, info), { type: 'ref', target: 'App\\Entity\\User', mode: 'random', index: 0 });
});
test('the sample of each generator', () => {
assert.equal(sample({ type: 'faker', formatter: 'sentence' }, info, 1), 'Eos qui amet.');
assert.equal(sample({ type: 'sequence', pattern: 'Post {n}', start: 5 }, info, 2), 'Post 7');
assert.equal(sample({ type: 'enum', class: 'App\\Enum\\Status', mode: 'random' }, info, 1), 'Status::Published');
assert.equal(sample({ type: 'enum', class: 'App\\Enum\\Status', mode: 'case', case: 'Draft' }, info), 'Status::Draft');
assert.equal(sample({ type: 'ref', target: 'App\\Entity\\User', mode: 'index', index: 3 }, info), '→ User #3');
assert.equal(sample({ type: 'refs', target: 'App\\Entity\\Tag', min: 1, max: 3 }, info), '→ 1-3 × Tag');
assert.equal(sample({ type: 'between', min: 10, max: 20, float: true, decimals: 1 }, info, 0).includes('.'), true);
assert.equal(sample({ type: 'skip' }, info), '—');
assert.equal(sampleRows(newModel(info, 'App\\Entity\\Post'), info, 2).length, 2);
});
test('a new model starts from the suggestions and goes to the PHP side cleaned', () => {
const m = newModel(info, 'App\\Entity\\Post');
assert.equal(m.class, 'PostFixtures');
assert.equal(m.fields.length, 4);
const c = cleanModel({ ...m, count: '12', groups: 'dev, demo', seed: '', fields: [{ name: 'n', generator: { type: 'between', min: '1', max: '5', cast: undefined } }] });
assert.equal(c.count, 12);
assert.deepEqual(c.groups, ['dev', 'demo']);
assert.equal(c.seed, null);
assert.deepEqual(c.fields[0].generator, { type: 'between', min: 1, max: 5 });
assert.equal(coerce('3'), 3);
assert.equal(coerce('true'), true);
assert.deepEqual(coerce('["a","b"]'), ['a', 'b']);
assert.equal(coerce('x'), 'x');
});
test('the fixtures a model waits for come from its relations', () => {
const m = newModel(info, 'App\\Entity\\Post');
assert.deepEqual(dependencies(m, info), ['App\\DataFixtures\\UserFixtures', 'App\\DataFixtures\\TagFixtures']);
});
test('the load line', () => {
assert.equal(loadLine({ mode: 'append', groups: ['dev'] }), 'php bin/console doctrine:fixtures:load --no-interaction --append --group=dev');
assert.equal(loadLine({ mode: 'purge', groups: [] }), 'php bin/console doctrine:fixtures:load --no-interaction');
});
// the test wizard ---------------------------------------------------------------------------------------------------------------
const tinfo = {
apiPlatform: false, userClass: 'App\\Entity\\User',
assertions: [
{ id: 'isSuccessful', label: 'Response is successful (2xx)', kinds: ['functional', 'api'], args: [], code: 'self::assertResponseIsSuccessful();' },
{ id: 'selectorTextContains', label: 'x', kinds: ['functional', 'panther'], args: [{ name: 'selector', default: "'h1'" }, { name: 'text', default: "'Hello'" }], code: 'self::assertSelectorTextContains({1}, {2});' },
{ id: 'same', label: 'y', kinds: ['unit', 'kernel'], args: [{ name: 'expected', default: "'expected'" }], code: 'self::assertSame({1}, $result);' },
{ id: 'notNull', label: 'z', kinds: ['unit', 'kernel'], args: [], code: 'self::assertNotNull($result);' },
{ id: 'statusCodeSame', label: 'w', kinds: ['functional', 'api'], args: [{ name: 'code', default: '200' }], code: 'self::assertResponseStatusCodeSame({1});' },
],
};
test('the kinds of test and their palette', () => {
assert.deepEqual(kindsFor(tinfo), ['unit', 'kernel', 'functional', 'panther']);
assert.deepEqual(kindsFor({ ...tinfo, apiPlatform: true }), KINDS);
assert.deepEqual(paletteFor('unit', tinfo).map((a) => a.id), ['same', 'notNull']);
for (const k of KINDS) assert.ok(KIND_LABELS[k]);
});
test('an assertion with its arguments, the defaults filling the blanks', () => {
assert.equal(assertionCode({ id: 'selectorTextContains', args: ["'h2'", ''] }, tinfo), "self::assertSelectorTextContains('h2', 'Hello');");
assert.deepEqual(newAssertion('same', tinfo), { id: 'same', args: ["'expected'"] });
});
test('new tests start with a name and a useful assertion', () => {
assert.equal(testName('unit', { method: 'greet' }), 'testGreet');
assert.equal(testName('functional', { route: { name: 'app_home', method: 'GET' } }), 'testAppHome');
assert.equal(testName('functional', { route: { name: 'app_save', method: 'POST' } }), 'testAppSavePost');
assert.equal(testName('api', { operation: { method: 'GET', path: '/api/books' } }), 'testGetApiBooks');
const f = newTest('functional', { route: { name: 'admin', path: '/admin', protected: true } }, tinfo);
assert.equal(f.protected, true);
assert.equal(f.asserts[0].id, 'isSuccessful');
const u = newTest('unit', { method: 'reset', returnsVoid: true }, tinfo);
assert.deepEqual(u.asserts, []);
assert.equal(newTest('unit', { method: 'greet' }, tinfo).asserts[0].id, 'notNull');
});
test('the model sent: only the ticked tests, the login on the protected ones', () => {
const login = defaultLogin(tinfo);
assert.equal(login.mode, 'entity');
assert.equal(defaultLogin({}).mode, 'memory');
const state = { kind: 'functional', class: 'App\\Tests\\XTest', target: '', login, tests: [
{ name: 'testA', on: true, protected: true, route: { path: '/a' }, asserts: [{ id: 'isSuccessful', args: [] }] }, { name: 'testB', on: false, asserts: [] }] };
const m = cleanTest(state);
assert.equal(m.tests.length, 1);
assert.equal(m.tests[0].login.userClass, 'App\\Entity\\User');
});
test('the route list: framework routes apart from the API ones, filtered by what is typed', () => {
const routes = [{ name: 'app_home', path: '/', controller: 'H::i' }, { name: '_api_/books_get', path: '/api/books' }, { name: 'app_login', path: '/login' }];
assert.deepEqual(filterRoutes(routes, '').map((r) => r.name), ['app_home', 'app_login']);
assert.deepEqual(filterRoutes(routes, 'log').map((r) => r.name), ['app_login']);
assert.deepEqual(filterRoutes(routes, '', { api: true }).map((r) => r.name), ['_api_/books_get']);
});
// the install flow, with a fake runner -------------------------------------------------------------------------------------------
test('the missing packages are required one after the other, as dev dependencies', async () => {
const log = [];
const r = await installPackages([{ package: 'doctrine/doctrine-fixtures-bundle' }, { package: 'fakerphp/faker' }], {
run: async (p) => (log.push(p), { code: 0 }), onStep: (p, i, n) => log.push(['step', p, i, n]),
});
assert.equal(r.status, 'installed');
assert.deepEqual(r.done, ['doctrine/doctrine-fixtures-bundle', 'fakerphp/faker']);
assert.deepEqual(log[1], { action: 'require', package: 'doctrine/doctrine-fixtures-bundle', dev: true });
assert.deepEqual(log[0], ['step', 'doctrine/doctrine-fixtures-bundle', 0, 2]);
});
test('the first failure stops the others', async () => {
const log = [];
const r = await installPackages([{ package: 'a/a' }, { package: 'b/b' }], { run: async (p) => (log.push(p.package), { code: p.package === 'a/a' ? 1 : 0 }) });
assert.deepEqual(r, { status: 'failed', done: [], failed: 'a/a' });
assert.deepEqual(log, ['a/a']);
assert.equal((await installPackages([], { run: async () => ({ code: 0 }) })).status, 'nothing');
assert.equal((await installPackages([{ package: 'a/a' }], { run: async () => { throw new Error('no composer'); } })).status, 'failed');
});