191 lines
9.5 KiB
JavaScript
191 lines
9.5 KiB
JavaScript
// Смоук-тест Promptly: REST + WS (комнаты, навигация, переменные, аудио, сессии,
|
|
// плагины, pass-through цепь графа)
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const WebSocket = require('ws');
|
|
|
|
const BASE = process.env.BASE || 'http://localhost:3045';
|
|
const WS = BASE.replace(/^http/, 'ws');
|
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
|
|
async function j(method, path, body) {
|
|
const res = await fetch(BASE + path, {
|
|
method,
|
|
headers: body ? { 'Content-Type': 'application/json' } : undefined,
|
|
body: body ? JSON.stringify(body) : undefined,
|
|
});
|
|
const text = await res.text();
|
|
try { return { status: res.status, data: JSON.parse(text) }; } catch { return { status: res.status, data: text }; }
|
|
}
|
|
|
|
function connect(query = '') {
|
|
return new Promise((resolve, reject) => {
|
|
const ws = new WebSocket(WS + '/' + query);
|
|
const messages = [];
|
|
ws.on('open', () => resolve({ ws, messages }));
|
|
ws.on('message', (raw) => messages.push(JSON.parse(raw.toString())));
|
|
ws.on('error', reject);
|
|
});
|
|
}
|
|
|
|
const waitMsg = async (client, type, timeout = 2000) => {
|
|
const start = Date.now();
|
|
while (Date.now() - start < timeout) {
|
|
const found = client.messages.find((m) => m.type === type);
|
|
if (found) return found;
|
|
await sleep(30);
|
|
}
|
|
return null;
|
|
};
|
|
|
|
let failures = 0;
|
|
const check = (name, cond) => {
|
|
console.log(`${cond ? '[ok] ' : '[FAIL]'} ${name}`);
|
|
if (!cond) failures += 1;
|
|
};
|
|
|
|
(async () => {
|
|
// 1. создание презентации
|
|
const created = await j('POST', '/api/presentations', {
|
|
title: 'Smoke Test',
|
|
slides: [
|
|
{ elements: [{ type: 'text', text: 'Слайд 1', x: 10, y: 10, w: 80, h: 30 }] },
|
|
{ elements: [{ type: 'text', text: 'Слайд 2' }] },
|
|
],
|
|
variables: { score: 0 },
|
|
});
|
|
check('POST /api/presentations → 201', created.status === 201);
|
|
const id = created.data.id;
|
|
check('id выдан', typeof id === 'string' && id.startsWith('pres_'));
|
|
check('2 слайда нормализованы', created.data.slides.length === 2);
|
|
|
|
// 2. обновление
|
|
const updated = await j('PUT', `/api/presentations/${id}`, { title: 'Smoke Test 2' });
|
|
check('PUT обновляет title', updated.status === 200 && updated.data.title === 'Smoke Test 2');
|
|
|
|
// 3. глобальный WS видит презентации
|
|
const global = await connect();
|
|
const presMsg = await waitMsg(global, 'presentations');
|
|
check('global WS: snapshot presentations', presMsg && presMsg.presentations.some((p) => p.id === id));
|
|
|
|
// 3b. реестр плагинов: создание, разбор функций в ноды, файл на диске, обновление, удаление
|
|
const pluginCode = `-- тестовый модуль\nfunction alpha(x)\n return { x = x }\nend\n\n-- @node Бета\nfunction beta()\n return { ok = true }\nend\n`;
|
|
const createdPlugin = await j('POST', '/api/plugins', {
|
|
name: 'Smoke Plugin', description: 'временный', color: '#22c55e', code: pluginCode,
|
|
});
|
|
check('POST /api/plugins → 201', createdPlugin.status === 201);
|
|
const pluginId = createdPlugin.data.id;
|
|
const pluginNodes = createdPlugin.data.nodes || [];
|
|
check('плагин разобран на функции-ноды', pluginNodes.length === 2, `${pluginNodes.length} нод`);
|
|
check('комментарий @node задаёт имя ноды', pluginNodes.some((node) => node.fn === 'beta' && node.name === 'Бета'));
|
|
const pluginFile = path.join(__dirname, '..', 'server', 'data', 'plugins', `${pluginId}.lua`);
|
|
check('исходник плагина записан на диск', fs.existsSync(pluginFile));
|
|
const pluginUpdate = await j('PUT', `/api/plugins/${pluginId}`, { code: `${pluginCode}\nfunction gamma()\n return 1\nend\n` });
|
|
check('PUT /api/plugins добавляет функцию-ноду', pluginUpdate.status === 200 && pluginUpdate.data.nodes.length === 3);
|
|
let pluginBroadcast = null;
|
|
for (let i = 0; i < 40; i++) {
|
|
pluginBroadcast = global.messages
|
|
.filter((m) => m.type === 'plugins')
|
|
.find((m) => (m.plugins || []).some((plugin) => plugin.id === pluginId && plugin.nodes.length === 3));
|
|
if (pluginBroadcast) break;
|
|
await sleep(30);
|
|
}
|
|
check('global WS: broadcast реестра плагинов', !!pluginBroadcast);
|
|
const pluginDeleted = await j('DELETE', `/api/plugins/${pluginId}`);
|
|
check('DELETE /api/plugins → ok', pluginDeleted.status === 200);
|
|
check('исходник удалённого плагина убран с диска', !fs.existsSync(pluginFile));
|
|
const pluginGone = await j('GET', `/api/plugins/${pluginId}`);
|
|
check('удалённый плагин → 404', pluginGone.status === 404);
|
|
|
|
// 3c. pass-through цепь: слайд → переход → слайд вычисляет навигацию
|
|
const chain = await j('POST', '/api/presentations', {
|
|
title: 'Chain Smoke',
|
|
slides: [
|
|
{ id: 's1', elements: [{ type: 'text', text: 'A' }] },
|
|
{ id: 's2', elements: [{ type: 'text', text: 'B' }] },
|
|
],
|
|
graph: {
|
|
transitions: [{ id: 't1', name: 'Переход', code: 'app.log("go")' }],
|
|
links: [
|
|
{ id: 'l1', from: { kind: 'slide', id: 's1', port: 'next' }, to: { kind: 'transition', id: 't1', port: 'in' } },
|
|
{ id: 'l2', from: { kind: 'transition', id: 't1', port: 'out' }, to: { kind: 'slide', id: 's2', port: 'in' } },
|
|
],
|
|
},
|
|
});
|
|
check('pass-through цепь сохранена', chain.status === 201 && chain.data.graph.links.length === 2);
|
|
check('jumps вычислен через переход', chain.data.graph.jumps.s1 && chain.data.graph.jumps.s1.next === 's2');
|
|
await j('DELETE', `/api/presentations/${chain.data.id}`);
|
|
|
|
// 4. комната докладчика + зрителя
|
|
const speaker = await connect(`?id=${id}&role=speaker`);
|
|
const audience = await connect(`?id=${id}&role=audience`);
|
|
const syncA = await waitMsg(audience, 'sync');
|
|
check('audience получает sync', syncA && syncA.slides.length === 2);
|
|
|
|
// 5. сессии видны на глобальном канале
|
|
let sessOk = false;
|
|
for (let i = 0; i < 40; i++) {
|
|
await sleep(40);
|
|
sessOk = global.messages.some((m) => m.type === 'sessions'
|
|
&& m.sessions.some((s) => s.presentationId === id && s.viewers === 1 && s.presenters === 1));
|
|
if (sessOk) break;
|
|
}
|
|
check('global WS: sessions со зрителем и докладчиком', sessOk);
|
|
|
|
// 6. навигация от докладчика приходит зрителю
|
|
speaker.ws.send(JSON.stringify({ type: 'navigate', slideIndex: 1 }));
|
|
// дождёмся второго sync у зрителя
|
|
let navigated = null;
|
|
for (let i = 0; i < 40; i++) {
|
|
navigated = audience.messages.filter((m) => m.type === 'sync').find((m) => m.slideIndex === 1);
|
|
if (navigated) break;
|
|
await sleep(30);
|
|
}
|
|
check('navigate синхронизирует зрителя', !!navigated);
|
|
|
|
// 7. переменные докладчика → зрителю
|
|
speaker.ws.send(JSON.stringify({ type: 'vars', vars: { score: 42 } }));
|
|
const varsMsg = await waitMsg(audience, 'vars');
|
|
check('vars доходят до зрителя', varsMsg && varsMsg.vars.score === 42);
|
|
|
|
// 8. аудио-команда → зрителю
|
|
speaker.ws.send(JSON.stringify({ type: 'audio', command: { action: 'play', id: 'a1', src: '/uploads/x.mp3' } }));
|
|
const audioMsg = await waitMsg(audience, 'audio');
|
|
check('audio-команда доходит до зрителя', audioMsg && audioMsg.command.action === 'play');
|
|
|
|
// 9. зритель не может управлять (ролевая модель)
|
|
audience.ws.send(JSON.stringify({ type: 'vars', vars: { hacked: true } }));
|
|
audience.ws.send(JSON.stringify({ type: 'navigate', slideIndex: 0 }));
|
|
await sleep(250);
|
|
const hacked = speaker.messages.find((m) => m.type === 'vars' && m.vars && m.vars.hacked);
|
|
check('зритель не может менять переменные', !hacked);
|
|
|
|
// 10. поздний зритель получает состояние аудио
|
|
const late = await connect(`?id=${id}&role=audience`);
|
|
const audioState = await waitMsg(late, 'audio-state');
|
|
check('поздний зритель получает audio-state', !!audioState);
|
|
|
|
// 11. остановка сессии через REST
|
|
const stopped = await j('DELETE', `/api/sessions/${id}`);
|
|
check('DELETE /api/sessions → ok', stopped.status === 200 && stopped.data.ok === true);
|
|
const ended = await waitMsg(audience, 'session-ended');
|
|
check('session-ended доходит до зрителей', !!ended);
|
|
|
|
// 12. дубликат и удаление
|
|
const dup = await j('POST', `/api/presentations/${id}/duplicate`);
|
|
check('duplicate создаёт копию', dup.status === 201 && dup.data.title.includes('копия'));
|
|
const del = await j('DELETE', `/api/presentations/${dup.data.id}`);
|
|
check('DELETE презентации', del.status === 200);
|
|
const del2 = await j('DELETE', `/api/presentations/${id}`);
|
|
check('DELETE исходной презентации', del2.status === 200);
|
|
|
|
// 13. 404 на удалённую
|
|
const gone = await j('GET', `/api/presentations/${id}`);
|
|
check('после удаления → 404', gone.status === 404);
|
|
|
|
global.ws.close(); speaker.ws.close(); audience.ws.close(); late.ws.close();
|
|
await sleep(100);
|
|
console.log(failures ? `\n[FAIL] Провалено: ${failures}` : '\n[ok] Все проверки пройдены');
|
|
process.exit(failures ? 1 : 0);
|
|
})().catch((err) => { console.error('FATAL', err); process.exit(2); });
|