352 lines
13 KiB
JavaScript
352 lines
13 KiB
JavaScript
'use strict';
|
|
// Paste-mirroring functional test for the Browser Farm grid.
|
|
// Loads the REAL manager/public/index.html in jsdom, stubs the manager
|
|
// API, injects a fake Neko overlay (wrap div holding a <canvas> and a
|
|
// transparent <textarea>, exactly like the Neko client) into each cell
|
|
// iframe, then proves:
|
|
// T1 a paste in the master dispatches a paste with the SAME text into
|
|
// all 7 followers (read back the way Neko's Overlay reads it:
|
|
// e.clipboardData.getData('text/plain')), with no feedback loop
|
|
// T2 the pasted-into cell becomes Master
|
|
// T3 paste mirroring stops when Sync is OFF
|
|
// T4 an empty / missing clipboardData pastes nothing into followers
|
|
// T5 (regression) keydown mirroring still works
|
|
// T6 fallback path: a follower whose window lacks ClipboardEvent and
|
|
// DataTransfer still receives the text
|
|
//
|
|
// jsdom (v31) does not implement ClipboardEvent or DataTransfer, so the
|
|
// test polyfills them on every window (top + each iframe) to simulate a
|
|
// real Chrome. The grid code itself does not depend on the polyfill: it
|
|
// falls back to a plain Event + a clipboardData-like object when the
|
|
// constructors are missing.
|
|
//
|
|
// Run: node paste-sync-test.js (from this directory)
|
|
// Exit code 0 = all assertions passed, 1 = at least one failed.
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const { JSDOM } = require('jsdom');
|
|
|
|
const HTML_PATH = path.join(__dirname, '..', 'manager', 'public', 'index.html');
|
|
|
|
let pass = 0;
|
|
let fail = 0;
|
|
const failures = [];
|
|
function check(name, cond, detail) {
|
|
if (cond) {
|
|
pass++;
|
|
console.log(' PASS ' + name);
|
|
} else {
|
|
fail++;
|
|
failures.push(name);
|
|
console.log(' FAIL ' + name + (detail ? ' (' + detail + ')' : ''));
|
|
}
|
|
}
|
|
|
|
// jsdom marks every synthetic event isTrusted=false and the flag is
|
|
// non-configurable, so a real user event cannot be faked by defining the
|
|
// property on the event. Instead, override the Event.prototype getter to
|
|
// consult a set of events the test marks as trusted. The grid's own
|
|
// synthetic events are never in the set, so they still read false —
|
|
// which is exactly how the loop-prevention check behaves in a real
|
|
// browser.
|
|
const trustedEvents = new WeakSet();
|
|
function installTrustedEvents(win) {
|
|
try {
|
|
Object.defineProperty(win.Event.prototype, 'isTrusted', {
|
|
get: function () {
|
|
return trustedEvents.has(this);
|
|
},
|
|
configurable: true,
|
|
});
|
|
} catch (e) { /* already overridden */ }
|
|
}
|
|
function markTrusted(ev) {
|
|
trustedEvents.add(ev);
|
|
return ev;
|
|
}
|
|
|
|
// Minimal ClipboardEvent / DataTransfer, enough to stand in for Chrome's.
|
|
// Neko's Overlay only calls clipboardData.getData('text/plain').
|
|
function installClipboardPolyfill(win) {
|
|
if (typeof win.DataTransfer !== 'function') {
|
|
win.DataTransfer = class DataTransfer {
|
|
constructor() {
|
|
this._data = {};
|
|
}
|
|
setData(type, value) {
|
|
this._data[type] = String(value);
|
|
}
|
|
getData(type) {
|
|
return this._data[type] || '';
|
|
}
|
|
get types() {
|
|
return Object.keys(this._data);
|
|
}
|
|
};
|
|
}
|
|
if (typeof win.ClipboardEvent !== 'function') {
|
|
win.ClipboardEvent = class ClipboardEvent extends win.Event {
|
|
constructor(type, init) {
|
|
super(type, init);
|
|
this.clipboardData = (init && init.clipboardData) || null;
|
|
}
|
|
};
|
|
}
|
|
}
|
|
|
|
function sleep(ms) {
|
|
return new Promise((r) => setTimeout(r, ms));
|
|
}
|
|
|
|
const BROWSERS = [];
|
|
for (let i = 1; i <= 8; i++) {
|
|
BROWSERS.push({
|
|
id: 'b' + i,
|
|
name: 'Browser ' + i,
|
|
uaKey: 'chrome_win',
|
|
uaLabel: 'Chrome Windows',
|
|
proxy: { type: 'direct' },
|
|
httpPort: 18080 + i,
|
|
udpStart: 52000 + (i - 1) * 100,
|
|
udpEnd: 52000 + (i - 1) * 100 + 99,
|
|
status: 'running',
|
|
token: 'tok-b' + i,
|
|
});
|
|
}
|
|
|
|
async function main() {
|
|
const html = fs.readFileSync(HTML_PATH, 'utf8');
|
|
|
|
const dom = new JSDOM(html, {
|
|
url: 'http://localhost/',
|
|
runScripts: 'dangerously',
|
|
pretendToBeVisual: true,
|
|
beforeParse(window) {
|
|
installClipboardPolyfill(window);
|
|
installTrustedEvents(window);
|
|
// Stub the manager API: authenticated, one UA preset, 8 running
|
|
// browsers with tokens (so every cell auto-connects).
|
|
window.fetch = (url) => {
|
|
if (url === '/api/me') {
|
|
return Promise.resolve({ json: () => Promise.resolve({ authenticated: true }) });
|
|
}
|
|
if (url === '/api/ua-presets') {
|
|
return Promise.resolve({
|
|
json: () => Promise.resolve({ presets: { chrome_win: { label: 'Chrome Windows', ua: 'x' } } }),
|
|
});
|
|
}
|
|
if (url === '/api/browsers') {
|
|
return Promise.resolve({ json: () => Promise.resolve({ browsers: BROWSERS }) });
|
|
}
|
|
return Promise.reject(new Error('unexpected fetch: ' + url));
|
|
};
|
|
},
|
|
});
|
|
const win = dom.window;
|
|
const doc = win.document;
|
|
|
|
// Wait for checkAuth -> startGrid -> loadPresets -> refresh to build the cells.
|
|
await sleep(300);
|
|
const cells = {};
|
|
for (let i = 1; i <= 8; i++) {
|
|
const id = 'b' + i;
|
|
const iframe = doc.querySelector('#cell-' + id + ' iframe');
|
|
if (!iframe) throw new Error('cell ' + id + ' did not build');
|
|
cells[id] = { iframe };
|
|
}
|
|
check('grid builds 8 cells', Object.keys(cells).length === 8);
|
|
|
|
// Inject a fake Neko overlay into each iframe and record what Neko
|
|
// would receive: a 'paste' listener that reads clipboardData exactly
|
|
// like Overlay.onPaste does, plus counters for loop detection.
|
|
for (let i = 1; i <= 8; i++) {
|
|
const id = 'b' + i;
|
|
const iframe = cells[id].iframe;
|
|
const idoc = iframe.contentDocument;
|
|
const iwin = idoc.defaultView;
|
|
installClipboardPolyfill(iwin);
|
|
installTrustedEvents(iwin);
|
|
// The iframe's document is stuck in 'loading' with no root element
|
|
// (jsdom never fetches the /bN/ URL). Initialise it with a minimal
|
|
// skeleton so the fake overlay has a <body> to live in; the pending
|
|
// navigation does not replace the document afterwards (verified).
|
|
idoc.open();
|
|
idoc.write('<!DOCTYPE html><html><head></head><body></body></html>');
|
|
idoc.close();
|
|
const wrap = idoc.createElement('div');
|
|
const canvas = idoc.createElement('canvas');
|
|
const ta = idoc.createElement('textarea');
|
|
wrap.appendChild(canvas);
|
|
wrap.appendChild(ta);
|
|
idoc.body.appendChild(wrap);
|
|
cells[id].ta = ta;
|
|
cells[id].iwin = iwin;
|
|
cells[id].nekoPastes = []; // texts the fake Neko handler read
|
|
cells[id].pasteCount = 0; // every paste event seen on this textarea
|
|
cells[id].keys = []; // keydown keys seen on this textarea
|
|
ta.addEventListener('paste', (e) => {
|
|
cells[id].pasteCount++;
|
|
const t = e.clipboardData ? e.clipboardData.getData('text/plain') : '';
|
|
cells[id].nekoPastes.push(t);
|
|
});
|
|
ta.addEventListener('keydown', (e) => {
|
|
cells[id].keys.push(e.key);
|
|
});
|
|
// Trigger the grid's pollForInput (it runs on iframe load).
|
|
iframe.dispatchEvent(new win.Event('load'));
|
|
}
|
|
|
|
// The grid polls every 500ms for the Neko input; give it time to find
|
|
// the injected textareas and attach the Sync listeners.
|
|
await sleep(900);
|
|
|
|
const syncBtn = doc.getElementById('syncBtn');
|
|
function setSync(on) {
|
|
if ((syncBtn.textContent === 'Sinkron: ON') !== on) syncBtn.click();
|
|
}
|
|
function masterBadgeVisible(id) {
|
|
const b = doc.querySelector('#cell-' + id + ' .badge.master');
|
|
return b && b.style.display !== 'none';
|
|
}
|
|
// Dispatch a paste the way a real user paste arrives: a trusted
|
|
// ClipboardEvent carrying the text in a DataTransfer.
|
|
function dispatchTrustedPaste(id, text, opts) {
|
|
const c = cells[id];
|
|
const o = opts || {};
|
|
let dt = null;
|
|
if (o.noClipboardData !== true) {
|
|
dt = new c.iwin.DataTransfer();
|
|
if (text) dt.setData('text/plain', text);
|
|
}
|
|
const ev = new c.iwin.ClipboardEvent('paste', {
|
|
bubbles: true,
|
|
cancelable: true,
|
|
clipboardData: dt,
|
|
});
|
|
// A real user paste is trusted; mark it so the grid's isTrusted
|
|
// gate lets it through (jsdom cannot fake the flag directly).
|
|
markTrusted(ev);
|
|
c.ta.dispatchEvent(ev);
|
|
}
|
|
function dispatchTrustedKey(id, key, code, keyCode) {
|
|
const c = cells[id];
|
|
const ev = new c.iwin.KeyboardEvent('keydown', {
|
|
bubbles: true,
|
|
cancelable: true,
|
|
key,
|
|
code,
|
|
ctrlKey: false,
|
|
shiftKey: false,
|
|
altKey: false,
|
|
metaKey: false,
|
|
});
|
|
// A real user keypress is trusted; mark it so the grid's isTrusted
|
|
// gate lets it through (jsdom cannot fake the flag directly).
|
|
try {
|
|
Object.defineProperty(ev, 'keyCode', { value: keyCode });
|
|
Object.defineProperty(ev, 'which', { value: keyCode });
|
|
} catch (e) { /* ignore */ }
|
|
markTrusted(ev);
|
|
c.ta.dispatchEvent(ev);
|
|
}
|
|
function followerPastes() {
|
|
const out = {};
|
|
for (let i = 2; i <= 8; i++) out['b' + i] = cells['b' + i].nekoPastes.slice();
|
|
return out;
|
|
}
|
|
|
|
// ---- T1: paste in the master reaches all 7 followers with the same text ----
|
|
console.log('T1: paste mirrors to all followers');
|
|
setSync(true);
|
|
check('Sync ON', syncBtn.textContent === 'Sinkron: ON');
|
|
dispatchTrustedPaste('b1', 'hello paste');
|
|
await sleep(50);
|
|
check('master (b1) got its own paste', JSON.stringify(cells.b1.nekoPastes) === JSON.stringify(['hello paste']), 'got ' + JSON.stringify(cells.b1.nekoPastes));
|
|
let allSame = true;
|
|
let allOnce = true;
|
|
for (let i = 2; i <= 8; i++) {
|
|
const c = cells['b' + i];
|
|
if (JSON.stringify(c.nekoPastes) !== JSON.stringify(['hello paste'])) allSame = false;
|
|
if (c.pasteCount !== 1) allOnce = false;
|
|
}
|
|
check('all 7 followers received the same text', allSame, JSON.stringify(followerPastes()));
|
|
check('no feedback loop (each follower saw exactly 1 paste)', allOnce,
|
|
Object.keys(followerPastes()).map((k) => k + ':' + cells[k].pasteCount).join(' '));
|
|
|
|
// ---- T2: the pasted-into cell becomes Master ----
|
|
console.log('T2: master selection');
|
|
check('b1 is Master after pasting', masterBadgeVisible('b1'));
|
|
check('b2 is not Master', !masterBadgeVisible('b2'));
|
|
|
|
// ---- T3: Sync OFF stops paste mirroring ----
|
|
console.log('T3: Sync OFF stops mirroring');
|
|
setSync(false);
|
|
check('Sync OFF', syncBtn.textContent === 'Sinkron: OFF');
|
|
dispatchTrustedPaste('b1', 'second paste');
|
|
await sleep(50);
|
|
let noneNew = true;
|
|
for (let i = 2; i <= 8; i++) {
|
|
if (JSON.stringify(cells['b' + i].nekoPastes) !== JSON.stringify(['hello paste'])) noneNew = false;
|
|
}
|
|
check('followers received nothing new while OFF', noneNew, JSON.stringify(followerPastes()));
|
|
check('master still got its own paste while OFF',
|
|
JSON.stringify(cells.b1.nekoPastes) === JSON.stringify(['hello paste', 'second paste']),
|
|
'got ' + JSON.stringify(cells.b1.nekoPastes));
|
|
|
|
// ---- T4: empty / missing clipboardData pastes nothing ----
|
|
console.log('T4: empty clipboard does nothing');
|
|
setSync(true);
|
|
dispatchTrustedPaste('b1', ''); // empty DataTransfer: getData -> ''
|
|
await sleep(50);
|
|
let stillOnlyFirst = true;
|
|
for (let i = 2; i <= 8; i++) {
|
|
if (JSON.stringify(cells['b' + i].nekoPastes) !== JSON.stringify(['hello paste'])) stillOnlyFirst = false;
|
|
}
|
|
check('empty text pastes nothing into followers', stillOnlyFirst, JSON.stringify(followerPastes()));
|
|
dispatchTrustedPaste('b1', 'ignored', { noClipboardData: true }); // clipboardData null
|
|
await sleep(50);
|
|
let stillOnlyFirst2 = true;
|
|
for (let i = 2; i <= 8; i++) {
|
|
if (JSON.stringify(cells['b' + i].nekoPastes) !== JSON.stringify(['hello paste'])) stillOnlyFirst2 = false;
|
|
}
|
|
check('null clipboardData pastes nothing into followers', stillOnlyFirst2, JSON.stringify(followerPastes()));
|
|
|
|
// ---- T5 (regression): keydown mirroring still works ----
|
|
console.log('T5: keydown mirroring regression');
|
|
dispatchTrustedKey('b1', 'a', 'KeyA', 65);
|
|
await sleep(50);
|
|
let keysOk = true;
|
|
for (let i = 2; i <= 8; i++) {
|
|
if (JSON.stringify(cells['b' + i].keys) !== JSON.stringify(['a'])) keysOk = false;
|
|
}
|
|
check('keydown mirrors to all 7 followers', keysOk,
|
|
Object.keys(cells).map((k) => k + ':' + JSON.stringify(cells[k].keys)).join(' '));
|
|
|
|
// ---- T6: fallback when a follower window lacks ClipboardEvent/DataTransfer ----
|
|
console.log('T6: fallback without ClipboardEvent/DataTransfer');
|
|
delete cells.b8.iwin.ClipboardEvent;
|
|
delete cells.b8.iwin.DataTransfer;
|
|
dispatchTrustedPaste('b1', 'fallback text');
|
|
await sleep(50);
|
|
check('b8 (no ClipboardEvent/DataTransfer) still received the text',
|
|
JSON.stringify(cells.b8.nekoPastes) === JSON.stringify(['hello paste', 'fallback text']),
|
|
'got ' + JSON.stringify(cells.b8.nekoPastes));
|
|
let othersOk = true;
|
|
for (let i = 2; i <= 7; i++) {
|
|
if (JSON.stringify(cells['b' + i].nekoPastes) !== JSON.stringify(['hello paste', 'fallback text'])) othersOk = false;
|
|
}
|
|
check('other followers still received the text', othersOk, JSON.stringify(followerPastes()));
|
|
|
|
// ---- summary ----
|
|
console.log('\n' + pass + ' passed, ' + fail + ' failed');
|
|
if (failures.length) console.log('failed: ' + failures.join(', '));
|
|
dom.window.close();
|
|
process.exit(fail ? 1 : 0);
|
|
}
|
|
|
|
main().catch((e) => {
|
|
console.error('TEST CRASHED: ' + (e && e.stack ? e.stack : e));
|
|
process.exit(1);
|
|
});
|