fix(e2e): browser drivers fail fast instead of hanging
test_legend_toggle_e2e hung 900 s in Firefox during the 032-063 run and passed on rerun: bidi.mjs and cdp.mjs waited for every reply without a deadline, and neither a closed socket nor a browser exit after start ever rejected a waiting command. The new tests/e2e/driver.mjs gives each command 240 s and names it on timeout, and fails every waiting command when the socket closes or the browser exits; both drivers use it, along with its plan reading. tests/test_e2e_drivers.py runs both drivers against a fake browser that dies while a command waits: 4.5 s now, a 60 s timeout on the old drivers. The two-browser legend e2e is green on the new drivers. The Firefox stall itself is still unexplained; the next one fails with the command's name. 🎯 Fix: 95 % 💥 Break: 3 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 92 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0fece7664a
commit
156e9a1e83
4 files changed
+133
-48
No files matched your search
+6
-24
@@ -1,14 +1,14 @@
|
||||
import {spawn} from "node:child_process";
|
||||
import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";
|
||||
import {mkdtempSync, rmSync, writeFileSync} from "node:fs";
|
||||
import {createServer} from "node:net";
|
||||
import {tmpdir} from "node:os";
|
||||
import {join} from "node:path";
|
||||
import {connect, readPlan} from "./driver.mjs";
|
||||
|
||||
// Args: <firefox binary> <plan.json>; the plan lists steps {width, height, url, wait, keys, drag, probe, shot, gesture} and
|
||||
// an optional init like cdp.mjs.
|
||||
// Prints {results, errors}: one probe value per step and every JavaScript error the page logged.
|
||||
const [binary, planFile] = process.argv.slice(2);
|
||||
const plan = JSON.parse(readFileSync(planFile, "utf8"));
|
||||
const {binary, plan} = readPlan();
|
||||
const profile = mkdtempSync(join(tmpdir(), "bidi-"));
|
||||
writeFileSync(join(profile, "user.js"), ['user_pref("media.navigator.streams.fake", true);', 'user_pref("media.navigator.permission.disabled", true);', 'user_pref("media.volume_scale", "0.0");', ""].join("\n"));
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
@@ -41,31 +41,13 @@ await new Promise((resolve, reject) => {
|
||||
socket.onopen = resolve;
|
||||
socket.onerror = reject;
|
||||
});
|
||||
const waiting = new Map();
|
||||
const errors = [];
|
||||
let next = 0;
|
||||
socket.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
const call = connect(socket, browser, "BiDi", (data) => (data.type === "error" ? new Error(`${data.error}: ${data.message}`) : null), (data) => {
|
||||
if (data.method === "log.entryAdded" && data.params.level === "error" && data.params.type === "javascript") {
|
||||
errors.push(data.params.text);
|
||||
}
|
||||
if (data.id && waiting.has(data.id)) {
|
||||
const {resolve, reject} = waiting.get(data.id);
|
||||
waiting.delete(data.id);
|
||||
if (data.type === "error") {
|
||||
reject(new Error(`${data.error}: ${data.message}`));
|
||||
} else {
|
||||
resolve(data.result);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function send(method, params) {
|
||||
next += 1;
|
||||
const id = next;
|
||||
socket.send(JSON.stringify({id, method, params}));
|
||||
return new Promise((resolve, reject) => waiting.set(id, {resolve, reject}));
|
||||
}
|
||||
});
|
||||
const send = (method, params) => call({method, params});
|
||||
|
||||
const results = [];
|
||||
try {
|
||||
|
||||
+6
-24
@@ -1,7 +1,8 @@
|
||||
import {spawn} from "node:child_process";
|
||||
import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";
|
||||
import {mkdtempSync, rmSync, writeFileSync} from "node:fs";
|
||||
import {tmpdir} from "node:os";
|
||||
import {join} from "node:path";
|
||||
import {connect, readPlan} from "./driver.mjs";
|
||||
|
||||
// Args: <chromium binary> <plan.json>; the plan lists steps {width, height, url, wait, keys, drag, probe, shot, media, gesture},
|
||||
// keys being real key presses (Enter, Tab, ArrowLeft, ArrowRight) on the focused element before the probe, drag
|
||||
@@ -9,8 +10,7 @@ import {join} from "node:path";
|
||||
// user activation like a click, an optional init, the text of a function every new document runs before its own scripts,
|
||||
// and an optional authenticator {credentialId, privateKey, rpId}: base64 id and PKCS#8 key of a passkey the page may sign with.
|
||||
// Prints {results, errors}: one probe value per step and every uncaught page exception.
|
||||
const [binary, planFile] = process.argv.slice(2);
|
||||
const plan = JSON.parse(readFileSync(planFile, "utf8"));
|
||||
const {binary, plan} = readPlan();
|
||||
const profile = mkdtempSync(join(tmpdir(), "cdp-"));
|
||||
// --no-sandbox: the agent sandbox already forbids the user namespaces Chromium's own sandbox needs.
|
||||
// --enable-unsafe-swiftshader: without a GPU, headless Chromium gives WebGL only through SwiftShader, which it no longer enables by itself.
|
||||
@@ -39,32 +39,14 @@ await new Promise((resolve, reject) => {
|
||||
socket.onopen = resolve;
|
||||
socket.onerror = reject;
|
||||
});
|
||||
const waiting = new Map();
|
||||
const errors = [];
|
||||
let next = 0;
|
||||
socket.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
const call = connect(socket, browser, "CDP",(data) => (data.error ? new Error(JSON.stringify(data.error)) : null), (data) => {
|
||||
if (data.method === "Runtime.exceptionThrown") {
|
||||
const details = data.params.exceptionDetails;
|
||||
errors.push(details.exception ? details.exception.description : details.text);
|
||||
}
|
||||
if (data.id && waiting.has(data.id)) {
|
||||
const {resolve, reject} = waiting.get(data.id);
|
||||
waiting.delete(data.id);
|
||||
if (data.error) {
|
||||
reject(new Error(JSON.stringify(data.error)));
|
||||
} else {
|
||||
resolve(data.result);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function send(method, params, sessionId) {
|
||||
next += 1;
|
||||
const id = next;
|
||||
socket.send(JSON.stringify({id, method, params, ...(sessionId ? {sessionId} : {})}));
|
||||
return new Promise((resolve, reject) => waiting.set(id, {resolve, reject}));
|
||||
}
|
||||
});
|
||||
const send = (method, params, sessionId) => call({method, params, ...(sessionId ? {sessionId} : {})});
|
||||
|
||||
const results = [];
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import {readFileSync} from "node:fs";
|
||||
|
||||
const ANSWER_MS = 240000;
|
||||
|
||||
// Returns {binary, plan}: the browser binary and the parsed plan.json named by the driver's two arguments.
|
||||
export function readPlan() {
|
||||
const [binary, planFile] = process.argv.slice(2);
|
||||
return {binary, plan: JSON.parse(readFileSync(planFile, "utf8"))};
|
||||
}
|
||||
|
||||
// Args: socket an open WebSocket to the browser; browser its spawned process; label names the protocol in errors;
|
||||
// failure(data) returns the Error a reply carries, else null; event(data) sees every message.
|
||||
// Returns call({method, ...}): sends it with a fresh id and resolves with the reply's result; it rejects on an error
|
||||
// reply, after ANSWER_MS without one, or once the socket closes or the browser exits.
|
||||
export function connect(socket, browser, label, failure, event) {
|
||||
const waiting = new Map();
|
||||
let next = 0;
|
||||
const failAll = (why) => {
|
||||
for (const {reject} of waiting.values()) {
|
||||
reject(new Error(why));
|
||||
}
|
||||
waiting.clear();
|
||||
};
|
||||
socket.onclose = () => failAll(`${label} socket closed`);
|
||||
browser.on("exit", (code) => failAll(`browser exited with ${code}`));
|
||||
socket.onmessage = (message) => {
|
||||
const data = JSON.parse(message.data);
|
||||
event(data);
|
||||
if (data.id && waiting.has(data.id)) {
|
||||
const {resolve, reject} = waiting.get(data.id);
|
||||
waiting.delete(data.id);
|
||||
const error = failure(data);
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve(data.result);
|
||||
}
|
||||
}
|
||||
};
|
||||
return (payload) => {
|
||||
next += 1;
|
||||
const id = next;
|
||||
socket.send(JSON.stringify({id, ...payload}));
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
waiting.delete(id);
|
||||
reject(new Error(`${payload.method} got no answer within ${ANSWER_MS} ms`));
|
||||
}, ANSWER_MS);
|
||||
const settle = (finish) => (value) => {
|
||||
clearTimeout(timer);
|
||||
finish(value);
|
||||
};
|
||||
waiting.set(id, {resolve: settle(resolve), reject: settle(reject)});
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
E2E = Path(__file__).resolve().parent / "e2e"
|
||||
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
BANNERS = {"bidi.mjs": "WebDriver BiDi listening on ws://127.0.0.1:{port}", "cdp.mjs": "DevTools listening on ws://127.0.0.1:{port}/devtools/browser/x"}
|
||||
|
||||
|
||||
def silent_server(held: list[socket.socket]) -> int:
|
||||
"""Args:
|
||||
held: receives the accepted connection, kept open and never answered.
|
||||
|
||||
Returns:
|
||||
The port of a WebSocket server that completes the handshake and then
|
||||
stays silent.
|
||||
"""
|
||||
server = socket.create_server(("127.0.0.1", 0))
|
||||
held.append(server)
|
||||
|
||||
def serve() -> None:
|
||||
connection, _ = server.accept()
|
||||
held.append(connection)
|
||||
request = connection.recv(4096).decode()
|
||||
key = next(line.split(":", 1)[1].strip() for line in request.split("\r\n") if line.lower().startswith("sec-websocket-key:"))
|
||||
accept = base64.b64encode(hashlib.sha1((key + GUID).encode()).digest()).decode()
|
||||
connection.sendall(f"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {accept}\r\n\r\n".encode())
|
||||
while connection.recv(4096):
|
||||
pass
|
||||
|
||||
threading.Thread(target=serve, daemon=True).start()
|
||||
return server.getsockname()[1]
|
||||
|
||||
|
||||
def close_all(sockets: list[socket.socket]) -> None:
|
||||
for item in sockets:
|
||||
item.close()
|
||||
|
||||
|
||||
class TestDrivers(unittest.TestCase):
|
||||
def test_a_driver_fails_fast_when_the_browser_dies_while_a_command_waits_for_its_answer(self):
|
||||
for driver, banner in BANNERS.items():
|
||||
with self.subTest(driver=driver), tempfile.TemporaryDirectory() as tmp:
|
||||
held: list[socket.socket] = []
|
||||
self.addCleanup(close_all, held)
|
||||
browser = Path(tmp) / "browser"
|
||||
browser.write_text(f"#!/bin/sh\necho '{banner.format(port=silent_server(held))}' >&2\nsleep 2\nexit 3\n", encoding="utf-8")
|
||||
browser.chmod(0o755)
|
||||
plan = Path(tmp) / "plan.json"
|
||||
plan.write_text(json.dumps({"steps": []}), encoding="utf-8")
|
||||
done = subprocess.run(["node", str(E2E / driver), str(browser), str(plan)], capture_output=True, text=True, timeout=60, check=False)
|
||||
self.assertNotEqual(done.returncode, 0, done.stdout)
|
||||
self.assertIn("browser exited with 3", done.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user