Compare commits

...
Author SHA1 Message Date
feder-cr ca0df05694 ci: a hunt that says if the double mouseover of a handle click is an exit and re-entry or a spurious event, on the Windows binary of an engine candidate
The first button.click() of test_the_nine_actions_reach_the_page_through_a_handle, 60 runs one after the other and 60 four at a time, with the page listening to mouseover, mouseout, mouseenter, mouseleave, every mousemove and the rect of the button, and the core's retry loop hooked. One JSON line per run with a verdict, a table in the log. The candidate is run 45621332479 with core v69.82.0.
2026-11-25 17:51:24 +01:00
6 changed files with 693 additions and 0 deletions

No files matched your search

@@ -0,0 +1,104 @@
# ─────────────────────────────────────────────────────────────────────────────
# candidate-handle-double-hover-hunt.yml - a MEASUREMENT, not a gate: on Windows, on the binary of an ENGINE CANDIDATE, is the double `mouseover` that
# `tests/test_element_handle_actions.py::test_the_nine_actions_reach_the_page_through_a_handle` saw once (page record ['hover', 'hover', 'click'])
# an EXIT AND RE-ENTRY of the pointer (a mouseout between the two) or a SPURIOUS second mouseover (none between)?
#
# The scenario is the first `query_selector("#bottone").click()` of that test, repeated with a fresh browser each time (tests/hunt_handle_double_hover_e2e.py):
# the page listens to mouseover, mouseout, mouseenter, mouseleave, every mousemove and the button's rect, and the core's retry loop is hooked (it logs nothing
# of its turns). 60 runs one after the other, then 60 four at a time (xdist -n 4, as the suite runs). One line of JSON per run, a verdict
# (single | exit-reentry | spurious | other | error), a table in the log.
#
# The candidate is named by two files of this branch (ci/candidate-run.txt, ci/candidate-core-ref.txt): the artifact asset-win-x86_64 of that run of `release`
# in oss-invisible/firefox_antidetect_patch, sealed as the gate of the candidate seals it (scripts/hunt_candidate_binary.py). The wrapper is this branch's code,
# installed with that core ref, as the gate installs it.
#
# ONE job, on a push to its own branch only. Green whatever it finds; red only when the scenario itself errored (a launch, a goto or a click that raised).
# ─────────────────────────────────────────────────────────────────────────────
name: candidate-handle-double-hover-hunt
on:
push:
branches: [hunt/handle-double-hover]
permissions:
contents: read
actions: read
# A hunt has a group of its own, unique to the run: a newer push never cancels a measurement that is half done (tests/test_ci_runs_once_per_commit.py).
concurrency:
group: ${{ github.workflow }}-${{ github.run_id }}
cancel-in-progress: false
env:
# reads the artifacts and the log of the candidate's run (the engine repository is public)
GH_TOKEN: ${{ github.token }}
GITHUB_TOKEN: ${{ github.token }}
# the core of the candidate, not the one the wrapper pins: the pair is mismatched on purpose, as the gate of the candidate runs it
INVISIBLE_CORE_PIN: allow
INVISIBLE_CORE_AUTOFIX: "off"
jobs:
handle-double-hover:
name: candidate-handle-double-hover (windows)
runs-on: windows-2022 # the image of wrapper.e2e.suite.windows.1 in the gate of the candidate
timeout-minutes: 75
defaults:
run:
shell: bash
env:
HUNT_OUT: ${{ github.workspace }}/hunt-out
PYTHONUNBUFFERED: "1"
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: The candidate is named (ci/candidate-run.txt, ci/candidate-core-ref.txt)
run: python scripts/hunt_candidate_binary.py check
- name: Install the core of the candidate, the wrapper and the test deps
run: |
set -e
CORE_GIT="git+https://github.com/oss-invisible/core@$(python scripts/hunt_candidate_binary.py core-ref)"
python -m pip install --upgrade pip
python -m pip install --quiet "$CORE_GIT"
python -m pip install --quiet ".[dev]"
python -m pip install --quiet --force-reinstall "$CORE_GIT"
python -m pip install --quiet "playwright==$(cat scripts/playwright_pin.txt)"
python scripts/hunt_candidate_binary.py verify-core
- name: The binary of the candidate (asset-win-x86_64), sealed
run: python scripts/hunt_candidate_binary.py fetch --leg win-x86_64 --dest "$RUNNER_TEMP/candidate"
- name: The GeoIP database (made by the repository, same bytes every run)
run: python scripts/ci_lab_geoip.py build --pin ci/geoip.json
- name: The security state (a fixed directory of the repository)
run: python scripts/ci_lab_security_state.py set --pin ci/security-state.pin.json
- name: Which candidate this hunt ran on
run: |
mkdir -p "$HUNT_OUT"
cp "$RUNNER_TEMP/candidate/candidate.json" "$HUNT_OUT/"
cat "$HUNT_OUT/candidate.json"
# no PYTEST_ADDOPTS, no rerun plugin, no suite's options: the file is named by its path and is in no row of ci/required-suites.json
- name: 60 runs one after the other (a fresh browser each)
run: |
HUNT_MODE=sequential HUNT_RUNS=60 python -m pytest tests/hunt_handle_double_hover_e2e.py -o addopts="" -p no:cacheprovider -p no:rerunfailures \
-m e2e -q -rf --timeout 420 --timeout-method thread
- name: 60 runs four at a time (xdist -n 4, as the suite runs)
if: always()
run: |
HUNT_MODE=parallel HUNT_RUNS=60 python -m pytest tests/hunt_handle_double_hover_e2e.py -o addopts="" -p no:cacheprovider -p no:rerunfailures \
-m e2e -q -rf --timeout 420 --timeout-method thread -n 4 --dist load
- name: Close every Firefox left
if: always()
run: |
taskkill //F //IM firefox.exe //T 2>/dev/null || true
echo "left: $(tasklist //FI 'IMAGENAME eq firefox.exe' 2>/dev/null | grep -ci firefox || true)"
- name: The summary (the verdicts, the retry turns, the sequence of every run that is not single)
if: always()
run: python scripts/hunt_handle_double_hover_summary.py "$HUNT_OUT"
- name: Upload the runs
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: handle-double-hover-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ github.workspace }}/hunt-out
if-no-files-found: warn
retention-days: 14
+1
View File
@@ -0,0 +1 @@
v69.82.0
+1
View File
@@ -0,0 +1 @@
45621332479
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""The engine of an ENGINE CANDIDATE for a hunt, instead of the published one.
A candidate is a run of the `release` workflow of oss-invisible/firefox_antidetect_patch (kind=candidate): it builds both legs and
uploads each as the artifact `asset-<leg>`. A hunt branch names the run in two one-line files, written when the hunt is launched:
ci/candidate-run.txt the id of that run
ci/candidate-core-ref.txt the ref of oss-invisible/core the candidate was gated with (its `core_ref` input)
Both hold `TODO` until then, and every command here refuses `TODO` first, so a push before the launch fails at once and says why.
python scripts/hunt_candidate_binary.py check # both files are filled in: exit 1 and a message if not
python scripts/hunt_candidate_binary.py core-ref # prints the core ref
python scripts/hunt_candidate_binary.py verify-core # the installed core IS the git install of that ref (as gate.yml asserts)
python scripts/hunt_candidate_binary.py seal-tag # prints the tag the candidate is sealed under, firefox-N-candidate
python scripts/hunt_candidate_binary.py fetch --leg win-x86_64 --dest DIR
# downloads asset-<leg>, extracts it, seals the binary, exports the env
`fetch` does what the gate of the candidate does with its own artifact (gate.yml of the engine repository): the one
`firefox-*-stealth-<leg>.*` archive of the artifact is extracted (zip on Windows, tar.gz on Linux), and
`python -m invisible_core seal --binary <exe> --tag <seal tag>` writes the seal the wrapper's launch is checked under, and DEST/candidate.json
says which run, core ref, seal tag and bytes the hunt ran on. It then writes to
$GITHUB_ENV (when set) and prints: FF and INVPW_BINARY_PATH (the binary) and INVISIBLE_SEAL_FILE (the seal).
The seal tag is the one the plan job of the candidate's run printed (`seal_tag=firefox-N-candidate`); when that log cannot be read it is
the last published `firefox-N` tag plus one, which is how the plan makes it, and the line says so.
Needs the GitHub CLI with GH_TOKEN (the engine repository is public: the token of the workflow reads its artifacts and logs).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
ENGINE_REPO = "oss-invisible/firefox_antidetect_patch"
CORE_URL = "https://github.com/oss-invisible/core"
RUN_FILE = ROOT / "ci" / "candidate-run.txt"
CORE_FILE = ROOT / "ci" / "candidate-core-ref.txt"
LEGS = ("win-x86_64", "linux-x86_64")
class Refused(Exception):
"""What the hunt cannot start without; the message is the whole explanation."""
def _line(path: Path, what: str) -> str:
try:
text = path.read_text(encoding="utf-8")
except OSError as exc:
raise Refused("%s cannot be read: %s" % (path.relative_to(ROOT).as_posix(), exc))
lines = [line.strip() for line in text.splitlines() if line.strip()]
if len(lines) != 1:
raise Refused("%s must hold exactly one line (%s), it holds %d" % (path.relative_to(ROOT).as_posix(), what, len(lines)))
if lines[0] == "TODO":
raise Refused("%s says TODO: this hunt has no candidate yet. Write %s there, commit and push again."
% (path.relative_to(ROOT).as_posix(), what))
return lines[0]
def run_id() -> str:
value = _line(RUN_FILE, "the id of the candidate's run of the release workflow of %s" % ENGINE_REPO)
if not re.fullmatch(r"[0-9]{6,}", value):
raise Refused("ci/candidate-run.txt must be a run id (digits only), it says %r" % value)
return value
def core_ref() -> str:
value = _line(CORE_FILE, "the core_ref the candidate was gated with (a branch, a tag or a 40-character sha of oss-invisible/core)")
if not re.fullmatch(r"[A-Za-z0-9._/-]+", value) or value.startswith(("-", "/")):
raise Refused("ci/candidate-core-ref.txt must be one ref of the core, it says %r" % value)
return value
def _gh(*args: str) -> str:
done = subprocess.run(["gh", *args], capture_output=True, text=True, encoding="utf-8", errors="replace")
if done.returncode:
raise Refused("gh %s failed: %s" % (" ".join(args[:3]), (done.stderr or done.stdout).strip()[:400]))
return done.stdout
def seal_tag(run: str) -> str:
try:
jobs = json.loads(_gh("api", "repos/%s/actions/runs/%s/jobs?per_page=100" % (ENGINE_REPO, run)))["jobs"]
plan = next(j["id"] for j in jobs if j["name"] == "plan")
log = _gh("api", "--allow-escape-sequences", "repos/%s/actions/jobs/%s/logs" % (ENGINE_REPO, plan))
found = re.findall(r"seal_tag=(firefox-[0-9]+-candidate)\b", log)
if found:
print("seal tag %s (the plan job of run %s)" % (found[-1], run), file=sys.stderr)
return found[-1]
raise Refused("the plan job's log has no seal_tag line")
except (Refused, StopIteration, KeyError, ValueError) as exc:
print("::warning::the seal tag could not be read from run %s (%s); using the last published tag plus one" % (run, exc), file=sys.stderr)
rows = subprocess.run(["git", "ls-remote", "--tags", "--refs", "https://github.com/%s" % ENGINE_REPO, "refs/tags/firefox-*"],
capture_output=True, text=True, check=True).stdout.splitlines()
numbers = [int(m.group(1)) for line in rows for m in [re.search(r"refs/tags/firefox-([0-9]+)$", line)] if m]
if not numbers:
raise Refused("no firefox-N tag in %s: the number of the candidate is unknown" % ENGINE_REPO)
return "firefox-%d-candidate" % (max(numbers) + 1)
def verify_core(ref: str) -> None:
"""The installed core is the git install of exactly `ref` (the assertion of gate.yml), read after importing the wrapper."""
from importlib.metadata import distribution, version
if re.fullmatch(r"[0-9a-f]{40}", ref):
want = ref
else:
rows = [line.split() for line in subprocess.run(["git", "ls-remote", CORE_URL, ref, ref + "^{}"], capture_output=True, text=True,
check=True).stdout.splitlines() if line.strip()]
peeled = [sha for sha, name in rows if name.endswith("^{}")] # an annotated tag: its commit, not the tag object
want = (peeled or [sha for sha, _ in rows] or [""])[0]
import invisible_playwright # noqa: F401 - the import-time pin repair runs here, as under pytest
raw = distribution("invisible-core").read_text("direct_url.json")
got = (json.loads(raw).get("vcs_info") or {}).get("commit_id") if raw else None
print("core under test: %s from %s" % (version("invisible-core"), got or "the index"))
if not want or got != want:
raise Refused("THE CORE UNDER TEST IS NOT %s: installed %s from %s, the ref is %s"
% (ref, version("invisible-core"), got or "the index", want or "not a ref of the core"))
def fetch(leg: str, dest: Path) -> dict:
run = run_id()
tag = seal_tag(run)
dest.mkdir(parents=True, exist_ok=True)
art = dest / "art"
_gh("run", "download", run, "-R", ENGINE_REPO, "-n", "asset-%s" % leg, "-D", str(art))
archives = sorted(art.glob("firefox-*-stealth-%s.*" % leg))
if len(archives) != 1:
raise Refused("expected one firefox-*-stealth-%s archive in the artifact asset-%s of run %s, found: %s"
% (leg, leg, run, [p.name for p in archives] or sorted(p.name for p in art.iterdir())))
ff = dest / "ff"
ff.mkdir(exist_ok=True)
if leg.startswith("win"):
with zipfile.ZipFile(archives[0]) as z:
z.extractall(ff)
exe = ff / "firefox.exe"
else:
subprocess.run(["tar", "xzf", str(archives[0]), "-C", str(ff)], check=True)
exe = ff / "firefox"
if exe.exists():
exe.chmod(exe.stat().st_mode | 0o111)
if not exe.exists():
raise Refused("the archive %s has no %s at its root" % (archives[0].name, exe.name))
seal = dest / "candidate.seal.json"
subprocess.run([sys.executable, "-m", "invisible_core", "seal", "--binary", str(exe), "--tag", tag, "-o", str(seal)], check=True)
record = {"engine_repo": ENGINE_REPO, "run_id": run, "core_ref": core_ref(), "seal_tag": tag, "leg": leg, "archive": archives[0].name,
"archive_sha256": hashlib.sha256(archives[0].read_bytes()).hexdigest(),
"binary_sha256": hashlib.sha256(exe.read_bytes()).hexdigest()}
(dest / "candidate.json").write_text(json.dumps(record, indent=2), encoding="utf-8")
env = {"FF": exe.resolve().as_posix(), "INVPW_BINARY_PATH": exe.resolve().as_posix(), "INVISIBLE_SEAL_FILE": seal.resolve().as_posix()}
target = os.environ.get("GITHUB_ENV")
if target:
with open(target, "a", encoding="utf-8", newline="\n") as handle:
handle.writelines("%s=%s\n" % kv for kv in env.items())
for key, value in env.items():
print("%s=%s" % (key, value))
print("candidate run %s, archive %s, sealed as %s" % (run, archives[0].name, tag), file=sys.stderr)
return env
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], formatter_class=argparse.RawDescriptionHelpFormatter)
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("check")
sub.add_parser("core-ref")
sub.add_parser("verify-core")
sub.add_parser("seal-tag")
f = sub.add_parser("fetch")
f.add_argument("--leg", choices=LEGS, required=True)
f.add_argument("--dest", required=True, type=Path)
args = parser.parse_args(argv)
try:
if args.command == "check":
print("candidate run %s, core ref %s" % (run_id(), core_ref()))
elif args.command == "core-ref":
print(core_ref())
elif args.command == "verify-core":
verify_core(core_ref())
elif args.command == "seal-tag":
print(seal_tag(run_id()))
else:
fetch(args.leg, args.dest)
except Refused as exc:
print("::error::%s" % exc)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""The summary of tests/hunt_handle_double_hover_e2e.py: reads every run-<mode>-<index>.json of a directory, writes runs.jsonl (one line per run)
and summary.txt, and prints the table: verdicts per mode, the retry turns against the verdict, and the sequence of every run that is not `single`.
python scripts/hunt_handle_double_hover_summary.py DIR
It judges nothing: the exit code is 0 whatever it finds (the pytest steps say whether the scenario itself errored).
"""
from __future__ import annotations
import collections
import json
import sys
from pathlib import Path
VERDICTS = ("single", "exit-reentry", "spurious", "other", "error")
def _brief(record: dict) -> str:
"""The page's events up to the first click on one line: `over(412,310 rel=body t=..) move... out(..) over(..) click(..)`."""
parts = []
for e in record.get("events", []):
name = e["type"].replace("mouse", "")
extra = ""
if e["type"] in ("mouseover", "mouseout", "mouseenter", "mouseleave"):
rel = e.get("rel") or {}
extra = "(%s,%s rel=%s t=%.1f)" % (e["x"], e["y"], rel.get("id") or rel.get("tag"), e["ts"])
elif e["type"] == "click":
extra = "(%s,%s t=%.1f)" % (e["x"], e["y"], e["ts"])
elif e["type"].startswith("doc-"):
extra = "(%s)" % e.get("target")
parts.append(name + extra)
if e["type"] == "click":
break
return " ".join(parts)
def main(argv=None) -> int:
root = Path((argv or sys.argv[1:] or ["."])[0])
records = []
for path in sorted(root.glob("run-*.json")):
try:
records.append(json.loads(path.read_text(encoding="utf-8")))
except (OSError, ValueError) as exc:
records.append({"mode": "?", "index": path.name, "verdict": "error", "error": "unreadable: %s" % exc})
with open(root / "runs.jsonl", "w", encoding="utf-8", newline="\n") as handle:
for record in records:
handle.write(json.dumps(record, separators=(",", ":")) + "\n")
lines = []
out = lines.append
modes = sorted({r.get("mode", "?") for r in records}) or ["-"]
out("== VERDICTS per mode (run = one fresh browser, one first button.click() of a handle)")
out("%-12s %6s " % ("mode", "runs") + " ".join("%12s" % v for v in VERDICTS) + " test-rule-red")
for mode in modes:
rows = [r for r in records if r.get("mode") == mode]
count = collections.Counter(r.get("verdict") for r in rows)
red = sum(1 for r in rows if r.get("ok") and not r.get("test_rule_passes"))
out("%-12s %6d " % (mode, len(rows)) + " ".join("%12d" % count.get(v, 0) for v in VERDICTS) + " %d" % red)
total = collections.Counter(r.get("verdict") for r in records)
out("HUNTTOTAL runs=%d %s" % (len(records), " ".join("%s=%d" % (v, total.get(v, 0)) for v in VERDICTS)))
live = sum(1 for r in records if r.get("hooks_live"))
out("the hooks on the core's retry loop saw the click in %d of %d runs" % (live, len(records)))
out("")
out("== RETRY TURNS (turns = center-point computations of the click's _retry) against the verdict")
by = collections.defaultdict(list)
for r in records:
if r.get("ok"):
by[r["verdict"]].append(r)
for verdict in VERDICTS:
rows = by.get(verdict, [])
if not rows:
continue
turns = collections.Counter(r.get("turns") for r in rows)
wrong = sum(1 for r in rows if r.get("wrong_hit_target"))
out("%-13s n=%-4d turns: %s runs with a WrongHitTarget: %d" % (
verdict, len(rows), ", ".join("%s turn(s) x%d" % (k, v) for k, v in sorted(turns.items(), key=lambda kv: str(kv[0]))), wrong))
out("")
out("== RUNS THAT ARE NOT single")
odd = [r for r in records if r.get("verdict") != "single"]
if not odd:
out("none")
for r in odd:
out("%s #%s [%s] verdict=%s word=%s turns=%s ordine=%s" % (r.get("mode"), r.get("index"), r.get("worker"), r.get("verdict"), r.get("word"),
r.get("turns"), r.get("ordine")))
if r.get("verdict") == "error":
out(" %s" % r.get("error"))
continue
out(" page: " + _brief(r))
out(" core sent: " + " ".join("%s(%.0f,%.0f)" % (m["type"].replace("mouse", ""), m["x"], m["y"]) for m in r.get("core_mouse", [])))
out(" rect changes: %s resize: %s layout-shifts: %s" % (r.get("rect_changes"), r.get("resize"), r.get("layout_shifts")))
for t in r.get("retries", []):
out(" retry: turns=%s runs=%s act=%s hit=%s exc=%s" % (t["center_point_calls"], t["run_calls"], t["act_on_target_calls"],
[v for _, v in t["hit_verdicts"]], [e[1] for e in t["exceptions"]]))
text = "\n".join(lines) + "\n"
(root / "summary.txt").write_text(text, encoding="utf-8")
sys.stdout.write(text)
return 0
if __name__ == "__main__":
sys.exit(main())
+285
View File
@@ -0,0 +1,285 @@
"""HUNT, not a test of the suites: the double `mouseover` of `handle.click()`, seen once on Windows.
The e2e `tests/test_element_handle_actions.py::test_the_nine_actions_reach_the_page_through_a_handle` went red once on the Windows leg of an engine
candidate with the page's record `['hover', 'hover', 'click']` where it expects `['hover', 'click']` first. Two readings of that:
* an EXIT AND RE-ENTRY of the pointer (a `mouseout` between the two `mouseover`): the pointer left the button and came back, which a human
does and a page may count;
* a SPURIOUS second `mouseover` (none between): the engine told the page the pointer entered twice, which no pointer does.
This file runs the same scenario (same page, same launch, same call) with the page listening to everything that tells them apart, and the core's
retry loop hooked (the core logs nothing of its turns), and writes ONE JSON line per run with a verdict:
single [mouseover, click]
exit-reentry two or more mouseover before the first click, a mouseout between each pair
spurious two mouseover before the first click with no mouseout between them
other no mouseover before the click, a mouseover then a mouseout and no new one, no click...
It is named `hunt_*` and not `test_*` on purpose: no suite collects it (`ci/required-suites.json` names files, and the e2e accounting collects
`test_*`). The hunt workflow runs it by its path, once with no xdist and once with `-n 4 --dist load` as the suite does:
HUNT_MODE=sequential|parallel HUNT_RUNS=60 HUNT_OUT=<dir> pytest tests/hunt_handle_double_hover_e2e.py ...
A run that finds a defect PASSES (the finding is the point); a run whose scenario errors (a launch that fails, a page that never loads, a click that
raises) writes verdict `error` and FAILS, so that the job says the measurement is not what it was meant to be.
"""
from __future__ import annotations
import http.server
import json
import os
import socket
import threading
import time
import traceback
from pathlib import Path
import pytest
from _servers import LocalServer
pytestmark = pytest.mark.e2e
MODE = os.environ.get("HUNT_MODE", "sequential")
RUNS = int(os.environ.get("HUNT_RUNS", "60"))
OUT = Path(os.environ.get("HUNT_OUT", "hunt-out"))
# The page of tests/test_element_handle_actions.py, as it is there (the button and the record the test reads), and below it the listeners of the hunt.
PAGE = b"""<!doctype html>
<html><head><title>handle actions</title></head><body>
<input id="testo" type="text">
<input id="daScrivere" type="text">
<button id="bottone" type="button">press me</button>
<input id="casella" type="checkbox">
<select id="tendina">
<option value="a">Alpha</option><option value="b">Beta</option>
</select>
<div id="passaggio">no</div>
<script>
window.registro = {click: 0, ordine: [], change: [], tasti: []};
const b = document.getElementById('bottone');
b.addEventListener('click', e => {
window.registro.click++; window.registro.fidato = e.isTrusted;
window.registro.ordine.push('click');
});
b.addEventListener('mouseover', () => window.registro.ordine.push('hover'));
window.registro.movimenti = 0;
b.addEventListener('mousemove', () => window.registro.movimenti++);
for (const id of ['casella','tendina'])
document.getElementById(id).addEventListener('change',
() => window.registro.change.push(id));
document.getElementById('daScrivere').addEventListener('keydown',
e => window.registro.tasti.push(e.key));
</script>
<script>
// THE HUNT: everything a page can see of the pointer around the button, with the rect of the button at each moment.
(() => {
const b = document.getElementById('bottone');
const H = window.hunt = {ev: [], moves: [], dmoves: [], rects: [], ro: [], shifts: [], frames: 0};
const epoch = e => performance.timeOrigin + e.timeStamp;
const rect = () => { const r = b.getBoundingClientRect(); return [r.x, r.y, r.width, r.height]; };
const rel = e => e.relatedTarget ? {id: e.relatedTarget.id || null, tag: e.relatedTarget.tagName} : null;
for (const type of ['mouseover', 'mouseout', 'mouseenter', 'mouseleave', 'click'])
b.addEventListener(type, e => H.ev.push({type, rel: rel(e), x: e.clientX, y: e.clientY, ts: e.timeStamp, t: epoch(e),
trusted: e.isTrusted, rect: rect()}));
b.addEventListener('mousemove', e => H.moves.push([e.clientX, e.clientY, e.timeStamp, epoch(e)]));
document.addEventListener('mousemove', e => {
if (H.dmoves.length < 3000) H.dmoves.push([e.clientX, e.clientY, e.target.id || e.target.tagName, e.timeStamp]);
}, true);
// what happens to the pointer OFF the button (the body it leaves to, the field next to it)
for (const type of ['mouseover', 'mouseout'])
document.addEventListener(type, e => {
if (e.target !== b) H.ev.push({type: 'doc-' + type, target: e.target.id || e.target.tagName, rel: rel(e),
x: e.clientX, y: e.clientY, ts: e.timeStamp, t: epoch(e)});
}, true);
try {
new ResizeObserver(es => es.forEach(en => H.ro.push([en.contentRect.width, en.contentRect.height,
performance.timeOrigin + performance.now()]))).observe(b);
} catch (e) { H.roError = String(e); }
try {
new PerformanceObserver(l => l.getEntries().forEach(en => H.shifts.push([en.value, en.startTime]))).observe({type: 'layout-shift', buffered: true});
} catch (e) { H.shiftsError = String(e); }
let last = rect().join();
const tick = () => {
H.frames++;
const now = rect().join();
if (now !== last) { H.rects.push({t: performance.timeOrigin + performance.now(), now, was: last}); last = now; }
requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
H.snap = () => ({rect: rect(), vw: innerWidth, vh: innerHeight, scrollY: scrollY, dpr: devicePixelRatio,
focus: document.hasFocus(), visibility: document.visibilityState,
t: performance.timeOrigin + performance.now()});
})();
</script>
</body></html>"""
def judge(events):
"""The verdict of one run, from the page's events in order (a pure function: tests/unit would be where it is tested, it is here with the hunt).
Only what precedes the FIRST click counts: `mouseover`, `mouseout`, `click` of the button. See the module docstring for the four words."""
short = {"mouseover": "o", "mouseout": "x", "click": "c"}
seq = []
for e in events:
if e["type"] in short:
seq.append(short[e["type"]])
if e["type"] == "click":
break
word = "".join(seq)
if not word.endswith("c"):
return "other", word
before = word[:-1]
if before == "o":
return "single", word
if before.count("o") >= 2:
overs = [i for i, ch in enumerate(before) if ch == "o"]
for first, second in zip(overs, overs[1:]):
if "x" not in before[first:second]:
return "spurious", word
return "exit-reentry", word
return "other", word
# ── the core's retry loop, hooked (it logs nothing of its turns) ────────────────────────────────────────────────────────
class _Recorder:
def __init__(self):
self.mouse = [] # every pointer event the core sent: the client side of the sequence the page records
self.retries = [] # one per `_retry`: turns, runs, hit-target verdicts, what each `_act_on_target` ended with
REC = _Recorder()
_hooked = False
def _now_ms():
return time.time() * 1000.0
def _install_hooks():
"""Class-level wrappers on `invisible_core.juggler.actions.Actions`, once per process. They record and call the original with the same
arguments: nothing is changed. A run where `mouse` stays empty says the hooks never saw the call (`hooks_live` false in its line)."""
global _hooked
if _hooked:
return
from invisible_core.juggler import actions as A
cls = A.Actions
mouse, retry, center, hit, act = (cls._mouse_event, cls._retry, cls._center_point, cls.hit_target, cls._act_on_target)
def _mouse_event(self, event_type, point, *a, **kw):
REC.mouse.append({"t": _now_ms(), "type": event_type, "x": point[0], "y": point[1], "buttons": kw.get("buttons"),
"at_ms": kw.get("at_ms"), "retry": len(REC.retries)})
return mouse(self, event_type, point, *a, **kw)
def _retry(self, selector, run, *a, **kw):
turn = {"selector": str(selector)[:60], "start": _now_ms(), "center_point_calls": 0, "run_calls": 0, "act_on_target_calls": 0,
"hit_verdicts": [], "exceptions": [], "end": None}
REC.retries.append(turn)
def counted(f, el, pt):
turn["run_calls"] += 1
return run(f, el, pt)
try:
return retry(self, selector, counted, *a, **kw)
finally:
turn["end"] = _now_ms()
def _center_point(self, *a, **kw):
if REC.retries:
REC.retries[-1]["center_point_calls"] += 1
return center(self, *a, **kw)
def hit_target(self, f, element, point):
verdict = hit(self, f, element, point)
if REC.retries:
REC.retries[-1]["hit_verdicts"].append([_now_ms(), verdict])
return verdict
def _act_on_target(self, *a, **kw):
if REC.retries:
REC.retries[-1]["act_on_target_calls"] += 1
try:
return act(self, *a, **kw)
except BaseException as exc:
if REC.retries:
REC.retries[-1]["exceptions"].append([_now_ms(), type(exc).__name__, str(exc)[:200]])
raise
cls._mouse_event, cls._retry, cls._center_point, cls.hit_target, cls._act_on_target = (
_mouse_event, _retry, _center_point, hit_target, _act_on_target)
_hooked = True
def _serve():
class H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(PAGE)))
self.end_headers()
self.wfile.write(PAGE)
def log_message(self, *a):
pass
s = socket.socket()
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
s.close()
srv = LocalServer(("127.0.0.1", port), H)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv, "http://127.0.0.1:%d/" % port
def _write(index, record):
OUT.mkdir(parents=True, exist_ok=True)
path = OUT / ("run-%s-%03d.json" % (MODE, index))
path.write_text(json.dumps(record, separators=(",", ":")) + "\n", encoding="utf-8")
@pytest.mark.parametrize("index", range(RUNS))
def test_hunt_the_first_click_of_a_handle(index, firefox_binary):
"""One fresh browser, the first `button.click()` of the test, and the page's whole account of it."""
from invisible_playwright import InvisiblePlaywright
_install_hooks()
REC.mouse.clear()
REC.retries.clear()
record = {"mode": MODE, "index": index, "pid": os.getpid(), "worker": os.environ.get("PYTEST_XDIST_WORKER", "main")}
srv, url = _serve()
try:
with InvisiblePlaywright(seed=4242, binary_path=firefox_binary, headless=True) as browser:
page = browser.new_context().new_page()
page.goto(url, wait_until="load", timeout=30_000)
button = page.query_selector("#bottone")
t0 = _now_ms()
button.click()
t1 = _now_ms()
# nothing is asked of the page before the click: the scenario is the test's (goto, query_selector, click)
after = page.evaluate("() => { const h = window.hunt; return {hunt: {ev: h.ev, moves: h.moves, dmoves: h.dmoves, rects: h.rects, "
"ro: h.ro, shifts: h.shifts, frames: h.frames}, registro: window.registro, snap: h.snap()}; }")
hunt = after["hunt"]
verdict, word = judge(hunt["ev"])
turns = [r["center_point_calls"] for r in REC.retries]
record.update({
"ok": True, "verdict": verdict, "word": word,
"ordine": after["registro"]["ordine"], "clicks": after["registro"]["click"], "trusted": after["registro"].get("fidato"),
"test_rule_passes": after["registro"]["ordine"][:2] == ["hover", "click"],
"click_ms": round(t1 - t0, 1),
"events": hunt["ev"], "moves": hunt["moves"], "doc_moves": hunt["dmoves"],
"rect_changes": hunt["rects"], "resize": hunt["ro"], "layout_shifts": hunt["shifts"], "frames": hunt["frames"],
"snap_after_click": after["snap"],
"hooks_live": bool(REC.mouse), "core_mouse": REC.mouse, "retries": REC.retries,
"turns": turns[0] if turns else None,
"run_calls": REC.retries[0]["run_calls"] if REC.retries else None,
"wrong_hit_target": sum(1 for r in REC.retries for x in r["exceptions"] if x[1] == "WrongHitTarget"),
})
_write(index, record)
except BaseException as exc:
record.update({"ok": False, "verdict": "error", "error": "%s: %s" % (type(exc).__name__, exc),
"traceback": traceback.format_exc()[-3000:], "core_mouse": REC.mouse, "retries": REC.retries})
_write(index, record)
raise
finally:
srv.shutdown()