Репозитории /
Promptly /
scripts/smoke.js
smoke.js
| 1 | // Смоук-тест Promptly: REST + WS (комнаты, навигация, переменные, аудио, сессии, |
| 2 | // плагины, pass-through цепь графа) |
| 3 | const fs = require('fs'); |
| 4 | const path = require('path'); |
| 5 | const WebSocket = require('ws'); |
| 6 | |
| 7 | const BASE = process.env.BASE || 'http://localhost:3045'; |
| 8 | const WS = BASE.replace(/^http/, 'ws'); |
| 9 | const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); |
| 10 | |
| 11 | async function j(method, path, body) { |
| 12 | const res = await fetch(BASE + path, { |
| 13 | method, |
| 14 | headers: body ? { 'Content-Type': 'application/json' } : undefined, |
| 15 | body: body ? JSON.stringify(body) : undefined, |
| 16 | }); |
| 17 | const text = await res.text(); |
| 18 | try { return { status: res.status, data: JSON.parse(text) }; } catch { return { status: res.status, data: text }; } |
| 19 | } |
| 20 | |
| 21 | function connect(query = '') { |
| 22 | return new Promise((resolve, reject) => { |
| 23 | const ws = new WebSocket(WS + '/' + query); |
| 24 | const messages = []; |
| 25 | ws.on('open', () => resolve({ ws, messages })); |
| 26 | ws.on('message', (raw) => messages.push(JSON.parse(raw.toString()))); |
| 27 | ws.on('error', reject); |
| 28 | }); |
| 29 | } |
| 30 | |
| 31 | const waitMsg = async (client, type, timeout = 2000) => { |
| 32 | const start = Date.now(); |
| 33 | while (Date.now() - start < timeout) { |
| 34 | const found = client.messages.find((m) => m.type === type); |
| 35 | if (found) return found; |
| 36 | await sleep(30); |
| 37 | } |
| 38 | return null; |
| 39 | }; |
| 40 | |
| 41 | let failures = 0; |
| 42 | const check = (name, cond) => { |
| 43 | console.log(`${cond ? '[ok] ' : '[FAIL]'} ${name}`); |
| 44 | if (!cond) failures += 1; |
| 45 | }; |
| 46 | |
| 47 | (async () => { |
| 48 | // 1. создание презентации |
| 49 | const created = await j('POST', '/api/presentations', { |
| 50 | title: 'Smoke Test', |
| 51 | slides: [ |
| 52 | { elements: [{ type: 'text', text: 'Слайд 1', x: 10, y: 10, w: 80, h: 30 }] }, |
| 53 | { elements: [{ type: 'text', text: 'Слайд 2' }] }, |
| 54 | ], |
| 55 | variables: { score: 0 }, |
| 56 | }); |
| 57 | check('POST /api/presentations → 201', created.status === 201); |
| 58 | const id = created.data.id; |
| 59 | check('id выдан', typeof id === 'string' && id.startsWith('pres_')); |
| 60 | check('2 слайда нормализованы', created.data.slides.length === 2); |
| 61 | |
| 62 | // 2. обновление |
| 63 | const updated = await j('PUT', `/api/presentations/${id}`, { title: 'Smoke Test 2' }); |
| 64 | check('PUT обновляет title', updated.status === 200 && updated.data.title === 'Smoke Test 2'); |
| 65 | |
| 66 | // 3. глобальный WS видит презентации |
| 67 | const global = await connect(); |
| 68 | const presMsg = await waitMsg(global, 'presentations'); |
| 69 | check('global WS: snapshot presentations', presMsg && presMsg.presentations.some((p) => p.id === id)); |
| 70 | |
| 71 | // 3b. реестр плагинов: создание, разбор функций в ноды, файл на диске, обновление, удаление |
| 72 | const pluginCode = `-- тестовый модуль\nfunction alpha(x)\n return { x = x }\nend\n\n-- @node Бета\nfunction beta()\n return { ok = true }\nend\n`; |
| 73 | const createdPlugin = await j('POST', '/api/plugins', { |
| 74 | name: 'Smoke Plugin', description: 'временный', color: '#22c55e', code: pluginCode, |
| 75 | }); |
| 76 | check('POST /api/plugins → 201', createdPlugin.status === 201); |
| 77 | const pluginId = createdPlugin.data.id; |
| 78 | const pluginNodes = createdPlugin.data.nodes || []; |
| 79 | check('плагин разобран на функции-ноды', pluginNodes.length === 2, `${pluginNodes.length} нод`); |
| 80 | check('комментарий @node задаёт имя ноды', pluginNodes.some((node) => node.fn === 'beta' && node.name === 'Бета')); |
| 81 | const pluginFile = path.join(__dirname, '..', 'server', 'data', 'plugins', `${pluginId}.lua`); |
| 82 | check('исходник плагина записан на диск', fs.existsSync(pluginFile)); |
| 83 | const pluginUpdate = await j('PUT', `/api/plugins/${pluginId}`, { code: `${pluginCode}\nfunction gamma()\n return 1\nend\n` }); |
| 84 | check('PUT /api/plugins добавляет функцию-ноду', pluginUpdate.status === 200 && pluginUpdate.data.nodes.length === 3); |
| 85 | let pluginBroadcast = null; |
| 86 | for (let i = 0; i < 40; i++) { |
| 87 | pluginBroadcast = global.messages |
| 88 | .filter((m) => m.type === 'plugins') |
| 89 | .find((m) => (m.plugins || []).some((plugin) => plugin.id === pluginId && plugin.nodes.length === 3)); |
| 90 | if (pluginBroadcast) break; |
| 91 | await sleep(30); |
| 92 | } |
| 93 | check('global WS: broadcast реестра плагинов', !!pluginBroadcast); |
| 94 | const pluginDeleted = await j('DELETE', `/api/plugins/${pluginId}`); |
| 95 | check('DELETE /api/plugins → ok', pluginDeleted.status === 200); |
| 96 | check('исходник удалённого плагина убран с диска', !fs.existsSync(pluginFile)); |
| 97 | const pluginGone = await j('GET', `/api/plugins/${pluginId}`); |
| 98 | check('удалённый плагин → 404', pluginGone.status === 404); |
| 99 | |
| 100 | // 3c. pass-through цепь: слайд → переход → слайд вычисляет навигацию |
| 101 | const chain = await j('POST', '/api/presentations', { |
| 102 | title: 'Chain Smoke', |
| 103 | slides: [ |
| 104 | { id: 's1', elements: [{ type: 'text', text: 'A' }] }, |
| 105 | { id: 's2', elements: [{ type: 'text', text: 'B' }] }, |
| 106 | ], |
| 107 | graph: { |
| 108 | transitions: [{ id: 't1', name: 'Переход', code: 'app.log("go")' }], |
| 109 | links: [ |
| 110 | { id: 'l1', from: { kind: 'slide', id: 's1', port: 'next' }, to: { kind: 'transition', id: 't1', port: 'in' } }, |
| 111 | { id: 'l2', from: { kind: 'transition', id: 't1', port: 'out' }, to: { kind: 'slide', id: 's2', port: 'in' } }, |
| 112 | ], |
| 113 | }, |
| 114 | }); |
| 115 | check('pass-through цепь сохранена', chain.status === 201 && chain.data.graph.links.length === 2); |
| 116 | check('jumps вычислен через переход', chain.data.graph.jumps.s1 && chain.data.graph.jumps.s1.next === 's2'); |
| 117 | await j('DELETE', `/api/presentations/${chain.data.id}`); |
| 118 | |
| 119 | // 4. комната докладчика + зрителя |
| 120 | const speaker = await connect(`?id=${id}&role=speaker`); |
| 121 | const audience = await connect(`?id=${id}&role=audience`); |
| 122 | const syncA = await waitMsg(audience, 'sync'); |
| 123 | check('audience получает sync', syncA && syncA.slides.length === 2); |
| 124 | |
| 125 | // 5. сессии видны на глобальном канале |
| 126 | let sessOk = false; |
| 127 | for (let i = 0; i < 40; i++) { |
| 128 | await sleep(40); |
| 129 | sessOk = global.messages.some((m) => m.type === 'sessions' |
| 130 | && m.sessions.some((s) => s.presentationId === id && s.viewers === 1 && s.presenters === 1)); |
| 131 | if (sessOk) break; |
| 132 | } |
| 133 | check('global WS: sessions со зрителем и докладчиком', sessOk); |
| 134 | |
| 135 | // 6. навигация от докладчика приходит зрителю |
| 136 | speaker.ws.send(JSON.stringify({ type: 'navigate', slideIndex: 1 })); |
| 137 | // дождёмся второго sync у зрителя |
| 138 | let navigated = null; |
| 139 | for (let i = 0; i < 40; i++) { |
| 140 | navigated = audience.messages.filter((m) => m.type === 'sync').find((m) => m.slideIndex === 1); |
| 141 | if (navigated) break; |
| 142 | await sleep(30); |
| 143 | } |
| 144 | check('navigate синхронизирует зрителя', !!navigated); |
| 145 | |
| 146 | // 7. переменные докладчика → зрителю |
| 147 | speaker.ws.send(JSON.stringify({ type: 'vars', vars: { score: 42 } })); |
| 148 | const varsMsg = await waitMsg(audience, 'vars'); |
| 149 | check('vars доходят до зрителя', varsMsg && varsMsg.vars.score === 42); |
| 150 | |
| 151 | // 8. аудио-команда → зрителю |
| 152 | speaker.ws.send(JSON.stringify({ type: 'audio', command: { action: 'play', id: 'a1', src: '/uploads/x.mp3' } })); |
| 153 | const audioMsg = await waitMsg(audience, 'audio'); |
| 154 | check('audio-команда доходит до зрителя', audioMsg && audioMsg.command.action === 'play'); |
| 155 | |
| 156 | // 9. зритель не может управлять (ролевая модель) |
| 157 | audience.ws.send(JSON.stringify({ type: 'vars', vars: { hacked: true } })); |
| 158 | audience.ws.send(JSON.stringify({ type: 'navigate', slideIndex: 0 })); |
| 159 | await sleep(250); |
| 160 | const hacked = speaker.messages.find((m) => m.type === 'vars' && m.vars && m.vars.hacked); |
| 161 | check('зритель не может менять переменные', !hacked); |
| 162 | |
| 163 | // 10. поздний зритель получает состояние аудио |
| 164 | const late = await connect(`?id=${id}&role=audience`); |
| 165 | const audioState = await waitMsg(late, 'audio-state'); |
| 166 | check('поздний зритель получает audio-state', !!audioState); |
| 167 | |
| 168 | // 11. остановка сессии через REST |
| 169 | const stopped = await j('DELETE', `/api/sessions/${id}`); |
| 170 | check('DELETE /api/sessions → ok', stopped.status === 200 && stopped.data.ok === true); |
| 171 | const ended = await waitMsg(audience, 'session-ended'); |
| 172 | check('session-ended доходит до зрителей', !!ended); |
| 173 | |
| 174 | // 12. дубликат и удаление |
| 175 | const dup = await j('POST', `/api/presentations/${id}/duplicate`); |
| 176 | check('duplicate создаёт копию', dup.status === 201 && dup.data.title.includes('копия')); |
| 177 | const del = await j('DELETE', `/api/presentations/${dup.data.id}`); |
| 178 | check('DELETE презентации', del.status === 200); |
| 179 | const del2 = await j('DELETE', `/api/presentations/${id}`); |
| 180 | check('DELETE исходной презентации', del2.status === 200); |
| 181 | |
| 182 | // 13. 404 на удалённую |
| 183 | const gone = await j('GET', `/api/presentations/${id}`); |
| 184 | check('после удаления → 404', gone.status === 404); |
| 185 | |
| 186 | global.ws.close(); speaker.ws.close(); audience.ws.close(); late.ws.close(); |
| 187 | await sleep(100); |
| 188 | console.log(failures ? `\n[FAIL] Провалено: ${failures}` : '\n[ok] Все проверки пройдены'); |
| 189 | process.exit(failures ? 1 : 0); |
| 190 | })().catch((err) => { console.error('FATAL', err); process.exit(2); }); |