tickets
All repositories: gitoria
12.7 KB
// tests/e2e-attachments.mjs (mission 020): E2E of tickets#27 in a REAL browser (lisbeth's test Chrome over CDP, ONE tab reused).// node tests/e2e-attachments.mjs <old|new> <port> <sid> <ticket path e.g. /antcolony/20> <shotdir> [targetId]// The app runs on loreana (copy of the data), reached from lisbeth's Chrome through a reverse ssh forward at 127.0.0.1:<port>.// DOM.setFileInputFiles paths are on lisbeth: /tmp/j3-files/{phone-390.png,desktop-1280.png,huge.bin}.import { writeFileSync } from 'node:fs';const [mode, port, sid, path, shotDir, tidArg] = process.argv.slice(2);const BASE = `http://127.0.0.1:${port}`, F = n => '/tmp/j3-files/' + n, sleep = ms => new Promise(r => setTimeout(r, ms));const list = await (await fetch('http://127.0.0.1:9223/json/list')).json();const tgt = tidArg ? list.find(t => t.id === tidArg) : list.find(t => t.type === 'page' && t.url.startsWith('about:blank') || t.url.startsWith('http://127.0.0.1:87'));const ws = new WebSocket(tgt.webSocketDebuggerUrl); await new Promise(r => ws.onopen = r);let id = 0; const pend = new Map(), evs = [];ws.onmessage = m => { const d = JSON.parse(m.data); if (d.id && pend.has(d.id)) { const [ok, bad] = pend.get(d.id); pend.delete(d.id); d.error ? bad(new Error(JSON.stringify(d.error))) : ok(d.result); } else evs.push(d); };const send = (method, params = {}) => new Promise((ok, bad) => { const i = ++id; pend.set(i, [ok, bad]); ws.send(JSON.stringify({ id: i, method, params })); });const ev = async x => { const r = await send('Runtime.evaluate', { expression: x, awaitPromise: true, returnByValue: true }); if (r.exceptionDetails) throw new Error(JSON.stringify(r.exceptionDetails).slice(0, 300)); return r.result.value; };const waitFor = async (x, label, t = 20000) => { for (const end = Date.now() + t; Date.now() < end;) { if (await ev(x).catch(() => false)) return true; await sleep(150); } console.log(' TIMEOUT waiting for', label); return false; };const rect = async sel => ev(`(() => { const e = document.querySelector(${JSON.stringify(sel)}); if (!e) return null; e.scrollIntoView({ block: 'center' }); const r = e.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2, w: r.width, h: r.height }; })()`);const click = async sel => { const r = await rect(sel); if (!r) throw new Error('no ' + sel); await sleep(100); const r2 = await rect(sel); for (const [type, extra] of [['mouseMoved', {}], ['mousePressed', { button: 'left', clickCount: 1 }], ['mouseReleased', { button: 'left', clickCount: 1 }]]) await send('Input.dispatchMouseEvent', { type, x: r2.x, y: r2.y, ...extra }); };const key = (k, code, vk, mod = 0, extra = {}) => send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: mod, key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk, ...extra }).then(() => send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: mod, key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }));const shot = async name => { const r = await send('Page.captureScreenshot', { format: 'png' }); writeFileSync(`${shotDir}/${name}.png`, Buffer.from(r.data, 'base64')); console.log(' shot', name); };const results = []; const check = (n, ok, d = '') => { results.push([n, !!ok]); console.log((ok ? 'PASS ' : 'FAIL ') + n + (ok ? '' : ' ' + d)); };const chooseFiles = async names => { const { root } = await send('DOM.getDocument'); const { nodeId } = await send('DOM.querySelector', { nodeId: root.nodeId, selector: '#commentform files-upload label.choose input[type=file]' }); await send('DOM.setFileInputFiles', { files: names.map(F), nodeId }); };const picked = () => ev(`[...document.querySelectorAll('#commentform files-upload li.picked')].map(li => li.querySelector('.name').textContent + ':' + (li.querySelector('img.thumb') ? li.querySelector('img.thumb').naturalWidth : 'kind'))`);const metrics = () => ev(`(() => { const W = window.innerWidth; const wide = [...document.querySelectorAll('body *')].filter(e => { const r = e.getBoundingClientRect(); return r.width > 0 && (r.right > W + 0.5 || r.left < -0.5); }).filter(e => !e.closest('[data-allow-scroll]')).slice(0, 5).map(e => e.tagName + '.' + e.className + ' ' + Math.round(e.getBoundingClientRect().right)); return { W, scrollW: document.documentElement.scrollWidth, wide }; })()`);const inputSizes = () => ev(`[...document.querySelectorAll('#commentform input:not([type=hidden]):not([type=file]), #commentform textarea, #commentform [contenteditable], #commentform md-editor article')].filter(e => e.getBoundingClientRect().width > 0).map(e => e.tagName + '.' + e.className + ' ' + parseFloat(getComputedStyle(e).fontSize))`);const targets = () => ev(`[...document.querySelectorAll('#events a.comment-thumb, #events a.comment-file, #commentform files-upload label.choose, #commentform files-upload label.camera, #commentform files-upload button.remove, #commentform button.comment-post, #commentform button[type=submit]')].filter(e => e.getBoundingClientRect().width > 0).map(el => { const r = el.getBoundingClientRect(); return el.tagName + '.' + el.className + ' ' + Math.round(r.width) + 'x' + Math.round(r.height); })`);await send('Page.enable'); await send('Runtime.enable'); await send('DOM.enable'); await send('Network.enable');await send('Network.setCookie', { name: 'hlsid', value: sid, url: BASE, httpOnly: true });const widths = [390, 1280];for (const W of widths) {const tag = `${mode}-${W}`;if (W === 390) await send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });else { await send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false }); }await send('Page.navigate', { url: BASE + path });await waitFor(`!!document.querySelector('#commentform')`, 'comment form');await sleep(1500);const n0 = await ev(`document.querySelectorAll('#events li.comment').length`);await rect('#commentform'); await sleep(300);await shot(`${tag}-form-before`);const m0 = await metrics(); const is0 = await inputSizes();console.log(`[${tag}] form`, JSON.stringify(m0), 'inputs', JSON.stringify(is0), 'targets', JSON.stringify(await targets()));if (W === 390) { check(`${tag}: nothing wider than 390 (scrollWidth ${m0.scrollW})`, m0.scrollW <= 390 && m0.wide.length === 0, JSON.stringify(m0)); check(`${tag}: inputs >= 16px`, is0.length > 0 && is0.every(s => +s.split(' ').pop() >= 16), JSON.stringify(is0)); }if (mode === 'old') continue;// 1. choose two picturesawait chooseFiles(['phone-390.png', 'desktop-1280.png']);await waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 2 && [...document.querySelectorAll('#commentform files-upload img.thumb')].every(i => i.complete && i.naturalWidth > 0)`, 'two thumbs');check(`${tag}: two chosen pictures wait as drawn thumbnails`, JSON.stringify(await picked()) === JSON.stringify(['phone-390.png:390', 'desktop-1280.png:1280']), JSON.stringify(await picked()));// 2. type text with real input, then paste a picture with real Ctrl+Vawait click('#commentform md-editor article'); await sleep(300);await send('Input.insertText', { text: `E2E ${tag}: two chosen, one pasted` });// CDP cannot fill lisbeth's system clipboard (navigator.clipboard.write says ok, a real Ctrl+V then pastes the user's old clipboard text),// and a real Ctrl+V would paste that private text into the form. So: a paste event dispatched on the focused editor carrying a File.const put = await ev(`(async () => { try { const c = document.createElement('canvas'); c.width = 160; c.height = 100; const x = c.getContext('2d'); x.fillStyle = '#246'; x.fillRect(0, 0, 160, 100); x.fillStyle = '#fc0'; x.fillRect(20, 20, 60, 40); const bl = await new Promise(r => c.toBlob(r, 'image/png')); const dt = new DataTransfer(); dt.items.add(new File([bl], 'image.png', { type: 'image/png' })); const t = document.querySelector('#commentform md-editor article'); t.focus(); t.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true })); return 'synthetic paste'; } catch (e) { return 'ERR ' + e.message; } })()`);await waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 3 && [...document.querySelectorAll('#commentform files-upload img.thumb')].every(i => i.complete && i.naturalWidth > 0)`, 'three thumbs', 8000);const pk = await picked();check(`${tag}: ${put} of a picture (real Ctrl+V impossible via CDP) adds the 3rd thumbnail (image.png:160)`, pk.length === 3 && pk[2] === 'image.png:160', JSON.stringify([put, pk]));await rect('#commentform files-upload'); await sleep(300); await shot(`${tag}-form-3thumbs`);// 3. remove one with the cross (first picked)await click('#commentform files-upload li.picked button.remove'); await sleep(500);const pk2 = await picked();check(`${tag}: ✕ removes one (2 left, first one gone)`, pk2.length === 2 && !pk2.some(x => x.startsWith('phone-390')), JSON.stringify(pk2));// 4. too bigawait chooseFiles(['huge.bin']);await waitFor(`document.querySelectorAll('#commentform files-upload li.refused').length === 1`, 'refused', 8000);const refusedTxt = await ev(`[...document.querySelectorAll('#commentform files-upload li.refused .state')].map(s => s.textContent).join()`);check(`${tag}: 11 MB file → "${refusedTxt}"`, /Too big/.test(refusedTxt) && (await picked()).length === 2, refusedTxt);const mf = await metrics(); const tg = await targets();console.log(`[${tag}] with files`, JSON.stringify(mf), 'targets', JSON.stringify(tg));await rect('#commentform files-upload'); await sleep(300); await shot(`${tag}-form-refused`);if (W === 390) {check(`${tag}: with picked + refused rows nothing wider than 390`, mf.scrollW <= 390 && mf.wide.length === 0, JSON.stringify(mf));check(`${tag}: tap targets >= 44 px (${tg.length} measured)`, tg.length >= 5 && tg.every(t => { const [w, h] = t.split(' ').pop().split('x').map(Number); return w >= 44 && h >= 44; }), JSON.stringify(tg));}// 5. send: Comment button at 390 (real click), Ctrl+Enter at 1280const stored0 = await ev(`document.querySelectorAll('#events li.comment').length`);if (W === 390) { await click('#commentform button.comment-post'); }else { await click('#commentform md-editor article'); await key('Enter', 'Enter', 13, 2, { text: '\r' }); }const sent = await waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 0 && [...document.querySelectorAll('#events li.comment')].some(li => li.querySelectorAll('ul.comment-files img').length === 2 && li.textContent.includes('E2E ${tag}'))`, 'posted', 30000);await sleep(1500);const th = await ev(`(() => { const li = [...document.querySelectorAll('#events li.comment')].filter(l => l.textContent.includes('E2E ${tag}')).pop(); return li ? [...li.querySelectorAll('ul.comment-files img')].map(i => [i.naturalWidth, Math.round(i.getBoundingClientRect().width), Math.round(i.getBoundingClientRect().height)]) : null; })()`);check(`${tag}: sent; the comment shows 2 thumbnails drawn (${JSON.stringify(th)}); the form is empty`, sent && th && th.length === 2 && th.every(x => x[0] > 0), JSON.stringify(th));await ev(`(() => { const li = [...document.querySelectorAll('#events li.comment')].filter(l => l.textContent.includes('E2E ${tag}')).pop(); li.scrollIntoView({ block: 'center' }); })()`); await sleep(400);await shot(`${tag}-comment-sent`);const m2 = await metrics();if (W === 390) check(`${tag}: after send nothing wider than 390`, m2.scrollW <= 390 && m2.wide.length === 0, JSON.stringify(m2));// 6. tap a thumbnail → full size in a new tab (we close that one tab ourselves)const before = new Set((await (await fetch('http://127.0.0.1:9223/json/list')).json()).map(t => t.id));const sel = `#events li.comment[data-id="${await ev(`[...document.querySelectorAll('#events li.comment')].filter(l => l.textContent.includes('E2E ${tag}')).pop().dataset.id`)}"] ul.comment-files li:nth-child(1) a.comment-thumb`;const href = await ev(`document.querySelector(${JSON.stringify(sel)}).getAttribute('href') + ' target=' + document.querySelector(${JSON.stringify(sel)}).target`);await click(sel);let opened = null; for (let i = 0; i < 30 && !opened; i++) { await sleep(250); opened = (await (await fetch('http://127.0.0.1:9223/json/list')).json()).find(t => !before.has(t.id) && t.type === 'page'); }check(`${tag}: tap on a thumbnail opens the full picture in a new tab (${href}) → ${opened && opened.url}`, !!opened && opened.url.startsWith(BASE + '/api/attachments/'), JSON.stringify(opened));if (opened) { await sleep(800); await fetch('http://127.0.0.1:9223/json/close/' + opened.id); }await send('Page.bringToFront');}await send('Emulation.clearDeviceMetricsOverride');const bad = results.filter(r => !r[1]);console.log(`\n${mode}: ${results.length - bad.length} passed, ${bad.length} failed`);ws.close(); process.exit(0);
Branches
Latest commits
- 5d144817Merge branch 'records-t40' into mainTickets
- 44ee6f06|||PR records: #43 #45 livemre
- b8fdeee9Merge branch 'p39-routes' into mainTickets
- a0187a0a|||PR Remove redundant route-order loopmre
- 369e4b9cMerge branch 'k40-lists' into mainTickets
- 9af8e780|||PR Use keyed list mutations for live ticket updatesmre
- 610d8e8aMerge branch 'records-t39' into mainTickets
- 32bcdf24|||PR records: GO P39 K40mre
- 4123c6d1Merge branch 'records-t38' into mainTickets
- cd3641a1|||PR records: day72 deploy live, tickets closedmre
- 7d44d852Merge branch 'records-t37' into mainTickets
- 926f7061|||PR records: merges, D36 deploymre
- bf58534eMerge branch 'l33-final' into mainTickets
- 759a9ac3|||PR thin login (tickets#46, #45): merge main, route entry cleanupmre
- 239436d8Merge remote-tracking branch 'origin/main' into l33-finalmre
- 5822cb3aMerge branch 'o34-clean' into mainTickets
- 0870653c|||PR offline note from __hlOnline, no polling (tickets#41)mre
- 14cf96b4Merge branch 'records-t36' into mainTickets
- 07749fa1|||PR records: day72 + #40 mergedmre
- ecd7e226|||PR Consolidate login and move handler logic into topic libraries (partial)mre