Paste sync test: final version, 17/17 pass
This commit is contained in:
1 parent
2efe74998c
commit
b600b92d76
1 file changed
+97
-82
@@ -1,5 +1,6 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
// Paste-mirroring functional test for the Browser Farm grid.
|
// Paste-mirroring functional test for the Browser Farm grid.
|
||||||
|
//
|
||||||
// Loads the REAL manager/public/index.html in jsdom, stubs the manager
|
// 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
|
// API, injects a fake Neko overlay (wrap div holding a <canvas> and a
|
||||||
// transparent <textarea>, exactly like the Neko client) into each cell
|
// transparent <textarea>, exactly like the Neko client) into each cell
|
||||||
@@ -8,17 +9,32 @@
|
|||||||
// all 7 followers (read back the way Neko's Overlay reads it:
|
// all 7 followers (read back the way Neko's Overlay reads it:
|
||||||
// e.clipboardData.getData('text/plain')), with no feedback loop
|
// e.clipboardData.getData('text/plain')), with no feedback loop
|
||||||
// T2 the pasted-into cell becomes Master
|
// T2 the pasted-into cell becomes Master
|
||||||
// T3 paste mirroring stops when Sync is OFF
|
// T3 paste mirroring stops when Sync is OFF, and a real (untrusted)
|
||||||
|
// paste event never mirrors (loop prevention)
|
||||||
// T4 an empty / missing clipboardData pastes nothing into followers
|
// T4 an empty / missing clipboardData pastes nothing into followers
|
||||||
// T5 (regression) keydown mirroring still works
|
// T5 (regression) keydown mirroring still works
|
||||||
// T6 fallback path: a follower whose window lacks ClipboardEvent and
|
// T6 fallback path: a follower whose window lacks ClipboardEvent and
|
||||||
// DataTransfer still receives the text
|
// DataTransfer still receives the text
|
||||||
|
// T7 the Neko input selector finds the overlay textarea, not a decoy
|
||||||
|
//
|
||||||
|
// Why the test drives the grid through an instrumented copy: jsdom
|
||||||
|
// cannot produce a trusted event — every event it creates has
|
||||||
|
// isTrusted=false (a non-configurable own property), and its
|
||||||
|
// dispatchEvent rejects Proxy-wrapped events. The grid's sync handler
|
||||||
|
// only mirrors trusted (real user) input, so a real DOM paste can never
|
||||||
|
// reach the mirroring code in jsdom. The test therefore loads an
|
||||||
|
// instrumented copy of the page (the production file is NOT modified:
|
||||||
|
// the script is the same, plus one export line exposing the sync
|
||||||
|
// functions) and invokes the handler with mock trusted events, while
|
||||||
|
// the DOM wiring (cells, iframes, input detection, listener attach) is
|
||||||
|
// exercised for real. A real untrusted DOM paste is also dispatched to
|
||||||
|
// prove the isTrusted gate blocks it.
|
||||||
//
|
//
|
||||||
// jsdom (v31) does not implement ClipboardEvent or DataTransfer, so the
|
// jsdom (v31) does not implement ClipboardEvent or DataTransfer, so the
|
||||||
// test polyfills them on every window (top + each iframe) to simulate a
|
// 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
|
// 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
|
// falls back to a plain Event + a clipboardData-like object when the
|
||||||
// constructors are missing.
|
// constructors are missing (see T6).
|
||||||
//
|
//
|
||||||
// Run: node paste-sync-test.js (from this directory)
|
// Run: node paste-sync-test.js (from this directory)
|
||||||
// Exit code 0 = all assertions passed, 1 = at least one failed.
|
// Exit code 0 = all assertions passed, 1 = at least one failed.
|
||||||
@@ -43,29 +59,6 @@ function check(name, cond, 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.
|
// Minimal ClipboardEvent / DataTransfer, enough to stand in for Chrome's.
|
||||||
// Neko's Overlay only calls clipboardData.getData('text/plain').
|
// Neko's Overlay only calls clipboardData.getData('text/plain').
|
||||||
function installClipboardPolyfill(win) {
|
function installClipboardPolyfill(win) {
|
||||||
@@ -118,13 +111,28 @@ for (let i = 1; i <= 8; i++) {
|
|||||||
async function main() {
|
async function main() {
|
||||||
const html = fs.readFileSync(HTML_PATH, 'utf8');
|
const html = fs.readFileSync(HTML_PATH, 'utf8');
|
||||||
|
|
||||||
const dom = new JSDOM(html, {
|
// Instrumented copy: the production script, plus one export line so
|
||||||
|
// the test can drive the sync handler with mock trusted events (see
|
||||||
|
// the header comment for why jsdom cannot dispatch a trusted event).
|
||||||
|
// The production file is left untouched.
|
||||||
|
const scriptMatch = html.match(/<script>([\s\S]*?)<\/script>/);
|
||||||
|
if (!scriptMatch) throw new Error('no <script> in index.html');
|
||||||
|
const script = scriptMatch[1];
|
||||||
|
const exportLine =
|
||||||
|
'\n window.__farmTest = { cells: cells, onCellInput: onCellInput, mirrorInput: mirrorInput, ' +
|
||||||
|
'setSync: setSync, setMaster: setMaster, clearMaster: clearMaster, ' +
|
||||||
|
'findNekoInput: findNekoInput, attachSyncListeners: attachSyncListeners, ' +
|
||||||
|
'getSyncOn: function () { return syncOn; }, getMasterId: function () { return masterId; } };';
|
||||||
|
if (!script.includes('\n checkAuth();\n})();')) throw new Error('script ending not found for instrumentation');
|
||||||
|
const instrumented = script.replace('\n checkAuth();\n})();', '\n checkAuth();' + exportLine + '\n})();');
|
||||||
|
const testHtml = html.replace(scriptMatch[0], '<script>' + instrumented + '</script>');
|
||||||
|
|
||||||
|
const dom = new JSDOM(testHtml, {
|
||||||
url: 'http://localhost/',
|
url: 'http://localhost/',
|
||||||
runScripts: 'dangerously',
|
runScripts: 'dangerously',
|
||||||
pretendToBeVisual: true,
|
pretendToBeVisual: true,
|
||||||
beforeParse(window) {
|
beforeParse(window) {
|
||||||
installClipboardPolyfill(window);
|
installClipboardPolyfill(window);
|
||||||
installTrustedEvents(window);
|
|
||||||
// Stub the manager API: authenticated, one UA preset, 8 running
|
// Stub the manager API: authenticated, one UA preset, 8 running
|
||||||
// browsers with tokens (so every cell auto-connects).
|
// browsers with tokens (so every cell auto-connects).
|
||||||
window.fetch = (url) => {
|
window.fetch = (url) => {
|
||||||
@@ -145,6 +153,8 @@ async function main() {
|
|||||||
});
|
});
|
||||||
const win = dom.window;
|
const win = dom.window;
|
||||||
const doc = win.document;
|
const doc = win.document;
|
||||||
|
const farm = win.__farmTest;
|
||||||
|
if (!farm) throw new Error('instrumentation failed: __farmTest missing');
|
||||||
|
|
||||||
// Wait for checkAuth -> startGrid -> loadPresets -> refresh to build the cells.
|
// Wait for checkAuth -> startGrid -> loadPresets -> refresh to build the cells.
|
||||||
await sleep(300);
|
await sleep(300);
|
||||||
@@ -166,7 +176,6 @@ async function main() {
|
|||||||
const idoc = iframe.contentDocument;
|
const idoc = iframe.contentDocument;
|
||||||
const iwin = idoc.defaultView;
|
const iwin = idoc.defaultView;
|
||||||
installClipboardPolyfill(iwin);
|
installClipboardPolyfill(iwin);
|
||||||
installTrustedEvents(iwin);
|
|
||||||
// The iframe's document is stuck in 'loading' with no root element
|
// The iframe's document is stuck in 'loading' with no root element
|
||||||
// (jsdom never fetches the /bN/ URL). Initialise it with a minimal
|
// (jsdom never fetches the /bN/ URL). Initialise it with a minimal
|
||||||
// skeleton so the fake overlay has a <body> to live in; the pending
|
// skeleton so the fake overlay has a <body> to live in; the pending
|
||||||
@@ -200,6 +209,8 @@ async function main() {
|
|||||||
// The grid polls every 500ms for the Neko input; give it time to find
|
// The grid polls every 500ms for the Neko input; give it time to find
|
||||||
// the injected textareas and attach the Sync listeners.
|
// the injected textareas and attach the Sync listeners.
|
||||||
await sleep(900);
|
await sleep(900);
|
||||||
|
const attached = Object.keys(farm.cells).filter((id) => farm.cells[id].inputEl).length;
|
||||||
|
check('grid found the Neko input in all 8 cells', attached === 8, 'found in ' + attached + '/8');
|
||||||
|
|
||||||
const syncBtn = doc.getElementById('syncBtn');
|
const syncBtn = doc.getElementById('syncBtn');
|
||||||
function setSync(on) {
|
function setSync(on) {
|
||||||
@@ -209,46 +220,24 @@ async function main() {
|
|||||||
const b = doc.querySelector('#cell-' + id + ' .badge.master');
|
const b = doc.querySelector('#cell-' + id + ' .badge.master');
|
||||||
return b && b.style.display !== 'none';
|
return b && b.style.display !== 'none';
|
||||||
}
|
}
|
||||||
// Dispatch a paste the way a real user paste arrives: a trusted
|
// Mock trusted events (plain objects): the grid's handler only reads
|
||||||
// ClipboardEvent carrying the text in a DataTransfer.
|
// these fields, and jsdom cannot create a trusted event. The
|
||||||
function dispatchTrustedPaste(id, text, opts) {
|
// clipboardData is a real DataTransfer from the master's window.
|
||||||
const c = cells[id];
|
function mockPaste(text, opts) {
|
||||||
const o = opts || {};
|
const o = opts || {};
|
||||||
let dt = null;
|
let dt = null;
|
||||||
if (o.noClipboardData !== true) {
|
if (!o.noClipboardData) {
|
||||||
dt = new c.iwin.DataTransfer();
|
dt = new cells.b1.iwin.DataTransfer();
|
||||||
if (text) dt.setData('text/plain', text);
|
if (text) dt.setData('text/plain', text);
|
||||||
}
|
}
|
||||||
const ev = new c.iwin.ClipboardEvent('paste', {
|
return { type: 'paste', isTrusted: true, clipboardData: dt };
|
||||||
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) {
|
function mockKey(key, code, keyCode) {
|
||||||
const c = cells[id];
|
return {
|
||||||
const ev = new c.iwin.KeyboardEvent('keydown', {
|
type: 'keydown', isTrusted: true, key, code, location: 0,
|
||||||
bubbles: true,
|
ctrlKey: false, shiftKey: false, altKey: false, metaKey: false,
|
||||||
cancelable: true,
|
repeat: false, keyCode, which: keyCode,
|
||||||
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() {
|
function followerPastes() {
|
||||||
const out = {};
|
const out = {};
|
||||||
@@ -256,13 +245,22 @@ async function main() {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- T7: the input selector finds the overlay textarea, not a decoy ----
|
||||||
|
console.log('T7: input selector vs decoy');
|
||||||
|
const decoy = cells.b1.ta.ownerDocument.createElement('textarea');
|
||||||
|
decoy.setAttribute('placeholder', 'chat');
|
||||||
|
cells.b1.ta.ownerDocument.body.appendChild(decoy); // no canvas parent: a chat box, not the Neko input
|
||||||
|
const found = farm.findNekoInput(cells.b1.ta.ownerDocument);
|
||||||
|
check('findNekoInput returns the overlay textarea, not the decoy', found === cells.b1.ta);
|
||||||
|
|
||||||
// ---- T1: paste in the master reaches all 7 followers with the same text ----
|
// ---- T1: paste in the master reaches all 7 followers with the same text ----
|
||||||
console.log('T1: paste mirrors to all followers');
|
console.log('T1: paste mirrors to all followers');
|
||||||
setSync(true);
|
setSync(true);
|
||||||
check('Sync ON', syncBtn.textContent === 'Sinkron: ON');
|
check('Sync ON', syncBtn.textContent === 'Sinkron: ON');
|
||||||
dispatchTrustedPaste('b1', 'hello paste');
|
farm.onCellInput('b1', mockPaste('hello paste'));
|
||||||
await sleep(50);
|
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));
|
// The master itself does not get a re-dispatched paste (only its own
|
||||||
|
// real one, which the mock stands in for — so it stays empty here).
|
||||||
let allSame = true;
|
let allSame = true;
|
||||||
let allOnce = true;
|
let allOnce = true;
|
||||||
for (let i = 2; i <= 8; i++) {
|
for (let i = 2; i <= 8; i++) {
|
||||||
@@ -279,42 +277,59 @@ async function main() {
|
|||||||
check('b1 is Master after pasting', masterBadgeVisible('b1'));
|
check('b1 is Master after pasting', masterBadgeVisible('b1'));
|
||||||
check('b2 is not Master', !masterBadgeVisible('b2'));
|
check('b2 is not Master', !masterBadgeVisible('b2'));
|
||||||
|
|
||||||
// ---- T3: Sync OFF stops paste mirroring ----
|
// ---- T3: Sync OFF stops mirroring; real untrusted paste never mirrors ----
|
||||||
console.log('T3: Sync OFF stops mirroring');
|
console.log('T3: Sync OFF + untrusted gate');
|
||||||
setSync(false);
|
setSync(false);
|
||||||
check('Sync OFF', syncBtn.textContent === 'Sinkron: OFF');
|
check('Sync OFF', syncBtn.textContent === 'Sinkron: OFF');
|
||||||
dispatchTrustedPaste('b1', 'second paste');
|
farm.onCellInput('b1', mockPaste('second paste'));
|
||||||
await sleep(50);
|
await sleep(50);
|
||||||
let noneNew = true;
|
let noneNew = true;
|
||||||
for (let i = 2; i <= 8; i++) {
|
for (let i = 2; i <= 8; i++) {
|
||||||
if (JSON.stringify(cells['b' + i].nekoPastes) !== JSON.stringify(['hello paste'])) noneNew = false;
|
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('followers received nothing new while OFF', noneNew, JSON.stringify(followerPastes()));
|
||||||
check('master still got its own paste while OFF',
|
// A real paste event dispatched on the master's textarea is untrusted
|
||||||
JSON.stringify(cells.b1.nekoPastes) === JSON.stringify(['hello paste', 'second paste']),
|
// in jsdom (as any synthetic event is in a real browser too): the
|
||||||
'got ' + JSON.stringify(cells.b1.nekoPastes));
|
// grid's listener must ignore it, so nothing mirrors.
|
||||||
|
|
||||||
// ---- T4: empty / missing clipboardData pastes nothing ----
|
|
||||||
console.log('T4: empty clipboard does nothing');
|
|
||||||
setSync(true);
|
setSync(true);
|
||||||
dispatchTrustedPaste('b1', ''); // empty DataTransfer: getData -> ''
|
const realPaste = new cells.b1.iwin.ClipboardEvent('paste', {
|
||||||
|
bubbles: true, cancelable: true, clipboardData: (() => {
|
||||||
|
const dt = new cells.b1.iwin.DataTransfer();
|
||||||
|
dt.setData('text/plain', 'real dom paste');
|
||||||
|
return dt;
|
||||||
|
})(),
|
||||||
|
});
|
||||||
|
cells.b1.ta.dispatchEvent(realPaste);
|
||||||
await sleep(50);
|
await sleep(50);
|
||||||
let stillOnlyFirst = true;
|
let stillOnlyFirst = true;
|
||||||
for (let i = 2; i <= 8; i++) {
|
for (let i = 2; i <= 8; i++) {
|
||||||
if (JSON.stringify(cells['b' + i].nekoPastes) !== JSON.stringify(['hello paste'])) stillOnlyFirst = false;
|
if (JSON.stringify(cells['b' + i].nekoPastes) !== JSON.stringify(['hello paste'])) stillOnlyFirst = false;
|
||||||
}
|
}
|
||||||
check('empty text pastes nothing into followers', stillOnlyFirst, JSON.stringify(followerPastes()));
|
check('real untrusted DOM paste mirrors nothing (loop prevention)', stillOnlyFirst,
|
||||||
dispatchTrustedPaste('b1', 'ignored', { noClipboardData: true }); // clipboardData null
|
JSON.stringify(followerPastes()));
|
||||||
|
check('master got its own real paste', JSON.stringify(cells.b1.nekoPastes) === JSON.stringify(['real dom paste']),
|
||||||
|
'got ' + JSON.stringify(cells.b1.nekoPastes));
|
||||||
|
|
||||||
|
// ---- T4: empty / missing clipboardData pastes nothing ----
|
||||||
|
console.log('T4: empty clipboard does nothing');
|
||||||
|
farm.onCellInput('b1', mockPaste('')); // empty DataTransfer: getData -> ''
|
||||||
await sleep(50);
|
await sleep(50);
|
||||||
let stillOnlyFirst2 = true;
|
let emptyOk = true;
|
||||||
for (let i = 2; i <= 8; i++) {
|
for (let i = 2; i <= 8; i++) {
|
||||||
if (JSON.stringify(cells['b' + i].nekoPastes) !== JSON.stringify(['hello paste'])) stillOnlyFirst2 = false;
|
if (JSON.stringify(cells['b' + i].nekoPastes) !== JSON.stringify(['hello paste'])) emptyOk = false;
|
||||||
}
|
}
|
||||||
check('null clipboardData pastes nothing into followers', stillOnlyFirst2, JSON.stringify(followerPastes()));
|
check('empty text pastes nothing into followers', emptyOk, JSON.stringify(followerPastes()));
|
||||||
|
farm.onCellInput('b1', mockPaste('ignored', { noClipboardData: true })); // clipboardData null
|
||||||
|
await sleep(50);
|
||||||
|
let nullOk = true;
|
||||||
|
for (let i = 2; i <= 8; i++) {
|
||||||
|
if (JSON.stringify(cells['b' + i].nekoPastes) !== JSON.stringify(['hello paste'])) nullOk = false;
|
||||||
|
}
|
||||||
|
check('null clipboardData pastes nothing into followers', nullOk, JSON.stringify(followerPastes()));
|
||||||
|
|
||||||
// ---- T5 (regression): keydown mirroring still works ----
|
// ---- T5 (regression): keydown mirroring still works ----
|
||||||
console.log('T5: keydown mirroring regression');
|
console.log('T5: keydown mirroring regression');
|
||||||
dispatchTrustedKey('b1', 'a', 'KeyA', 65);
|
farm.onCellInput('b1', mockKey('a', 'KeyA', 65));
|
||||||
await sleep(50);
|
await sleep(50);
|
||||||
let keysOk = true;
|
let keysOk = true;
|
||||||
for (let i = 2; i <= 8; i++) {
|
for (let i = 2; i <= 8; i++) {
|
||||||
@@ -327,7 +342,7 @@ async function main() {
|
|||||||
console.log('T6: fallback without ClipboardEvent/DataTransfer');
|
console.log('T6: fallback without ClipboardEvent/DataTransfer');
|
||||||
delete cells.b8.iwin.ClipboardEvent;
|
delete cells.b8.iwin.ClipboardEvent;
|
||||||
delete cells.b8.iwin.DataTransfer;
|
delete cells.b8.iwin.DataTransfer;
|
||||||
dispatchTrustedPaste('b1', 'fallback text');
|
farm.onCellInput('b1', mockPaste('fallback text'));
|
||||||
await sleep(50);
|
await sleep(50);
|
||||||
check('b8 (no ClipboardEvent/DataTransfer) still received the text',
|
check('b8 (no ClipboardEvent/DataTransfer) still received the text',
|
||||||
JSON.stringify(cells.b8.nekoPastes) === JSON.stringify(['hello paste', 'fallback text']),
|
JSON.stringify(cells.b8.nekoPastes) === JSON.stringify(['hello paste', 'fallback text']),
|
||||||
|
|||||||
Reference in new issue
Block a user