For each select the record now has, before the click and right after it: chrome Services.focus.activeWindow === win, win.document.hasFocus(), the browsing context's isActive (win.gBrowser.selectedBrowser.browsingContext.isActive), the top content document's hasFocus() and visibilityState, and the driver's ack of the click when it keeps one. A popup that does not open for a window that was not active is then told apart from a popup at the wrong place. A read that fails is recorded and never raised. Red on the old code: the six new tests and the existing ones that use the fake chrome fail without the read. unit.all rows: +6 (Linux 4357, Windows 4369).
152 lines
8.8 KiB
Python
152 lines
8.8 KiB
Python
"""What a popup twin records about each element it clicks, so that a red run says what the click and the geometry were, and a green run leaves the numbers to compare.
|
|
|
|
A twin that clicks an element and waits for a popup (the select dropdown) used to say "the dropdown did not open" and nothing about the click: where it was sent, at which scale, what the
|
|
element's box was in its document and in the window, and what the popup was doing. This module is what the twin keeps for each element, and writes:
|
|
|
|
* ``click``: the point in CSS pixels, and the point the driver sent (the unit it is in and the device point it makes: CSS times the scale the driver knows);
|
|
* ``scales``: the record of ``Driver.scales()`` (the page's and the chrome's ``devicePixelRatio`` and the real scale of the screen), once per browser;
|
|
* ``select_rect``: ``getBoundingClientRect`` of the element inside its own document, and, for an element of a frame, ``iframe_rect``: the frame element's box in the top document;
|
|
* ``mozInnerScreen``: ``window.mozInnerScreenX/Y`` of the top document and, for a frame, of the frame's document;
|
|
* ``activation_at_click`` and ``activation_after_click``: whether the window was the active one, and had the focus, when the click was sent and right after (``look_at_activation``): chrome
|
|
``Services.focus.activeWindow === win``, ``win.document.hasFocus()``, the browsing context's ``isActive`` (``win.gBrowser.selectedBrowser.browsingContext.isActive``), the top content document's
|
|
``hasFocus()`` and ``visibilityState``, and the driver's ack of the click when it has one (``last_click_ack``); a popup that does not open for a window that was not active is not a popup that is at the wrong place;
|
|
* ``popup``: the state after the click (the first look), the last look of the wait (at the deadline) and, when the popup did not reach the state, a second look (the select test: a short wait on the same condition, so that a popup that comes late is seen to come late).
|
|
|
|
A read that fails is recorded in ``errors`` and never raised: the diagnosis must not replace the finding. The record is in the message of the failure and, on a runner (``RUNNER_TEMP`` set), in
|
|
``$RUNNER_TEMP/invpw-evidence/popup-diagnostics/<case>-<browser>.json``, the folder every e2e job uploads (see ``_watchdog_log``), whatever the result.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
from typing import Any, Dict, Mapping, Optional, Sequence
|
|
|
|
from _watchdog_log import EVIDENCE_FOLDER
|
|
|
|
#: The folder of this evidence inside ``$RUNNER_TEMP/invpw-evidence``.
|
|
SUBFOLDER = "popup-diagnostics"
|
|
|
|
#: The top document: the element's box, the frame element's box, the window's place on the screen. Both ids are given by the page of the twin.
|
|
TOP_GEOMETRY_JS = """(() => {
|
|
const box = id => { const e = document.getElementById(id); if (!e) { return null; } const b = e.getBoundingClientRect(); return {x: b.x, y: b.y, w: b.width, h: b.height}; };
|
|
return {select: box(%(select)s), iframe: box(%(iframe)s), mozInnerScreen: [window.mozInnerScreenX, window.mozInnerScreenY], scroll: [window.scrollX, window.scrollY]};
|
|
})()"""
|
|
|
|
#: The document of a frame: the element's box inside it and its own place on the screen.
|
|
FRAME_GEOMETRY_JS = """(() => {
|
|
const e = document.getElementById(%(select)s); const b = e ? e.getBoundingClientRect() : null;
|
|
return {select: b && {x: b.x, y: b.y, w: b.width, h: b.height}, mozInnerScreen: [window.mozInnerScreenX, window.mozInnerScreenY], scroll: [window.scrollX, window.scrollY]};
|
|
})()"""
|
|
|
|
|
|
#: Chrome scope: the window's activation and focus, and the browsing context of the selected tab. ``win`` is the most recent browser window, as every chrome script of the twins reads it.
|
|
ACTIVATION_JS = """
|
|
const win = Services.wm.getMostRecentWindow("navigator:browser");
|
|
return JSON.stringify({
|
|
active_window: Services.focus.activeWindow === win,
|
|
window_has_focus: win.document.hasFocus(),
|
|
browsing_context_is_active: win.gBrowser.selectedBrowser.browsingContext.isActive,
|
|
});
|
|
"""
|
|
|
|
#: The top content document, read through the driver (``driver.eval``): the same expression on every driver.
|
|
CONTENT_ACTIVATION_JS = """(() => ({hasFocus: document.hasFocus(), visibilityState: document.visibilityState}))()"""
|
|
|
|
|
|
def _failed(exc: BaseException) -> str:
|
|
return "%s: %s" % (type(exc).__name__, str(exc)[:300])
|
|
|
|
|
|
def look_at_geometry(driver: Any, in_frame: bool, select_id: str = "s", frame_id: str = "f") -> Dict[str, Any]:
|
|
"""The boxes and the window's place for one element, read before the click. ``driver.eval`` reads the top document, ``driver.eval_in_frame`` the frame's.
|
|
A read that fails leaves its field out and says why in ``errors``."""
|
|
ids = {"select": json.dumps(select_id), "iframe": json.dumps(frame_id)}
|
|
out: Dict[str, Any] = {"errors": {}}
|
|
top: Optional[Dict[str, Any]] = None
|
|
try:
|
|
top = driver.eval(TOP_GEOMETRY_JS % ids)
|
|
except Exception as exc: # noqa: BLE001 the diagnosis never replaces the finding
|
|
out["errors"]["top_document"] = _failed(exc)
|
|
top = top or {}
|
|
out["mozInnerScreen"] = {"top": top.get("mozInnerScreen")}
|
|
if not in_frame:
|
|
out["select_rect"] = top.get("select")
|
|
out["iframe_rect"] = None
|
|
else:
|
|
out["iframe_rect"] = top.get("iframe")
|
|
try:
|
|
inner = driver.eval_in_frame(FRAME_GEOMETRY_JS % ids)
|
|
out["select_rect"] = inner.get("select")
|
|
out["mozInnerScreen"]["frame"] = inner.get("mozInnerScreen")
|
|
except Exception as exc: # noqa: BLE001
|
|
out["errors"]["frame_document"] = _failed(exc)
|
|
out["select_rect"] = None
|
|
out["mozInnerScreen"]["frame"] = None
|
|
if not out["errors"]:
|
|
del out["errors"]
|
|
return out
|
|
|
|
|
|
def look_at_activation(driver: Any) -> Dict[str, Any]:
|
|
"""The window's activation and focus now: the chrome's (``ACTIVATION_JS``), the top content document's (``CONTENT_ACTIVATION_JS``) and the driver's ack of the click, when it keeps one
|
|
(``last_click_ack``, None otherwise). A read that fails leaves its part out and says why in ``errors``; the diagnosis never replaces the finding."""
|
|
out: Dict[str, Any] = {"errors": {}}
|
|
try:
|
|
out["chrome"] = driver.chrome.script(ACTIVATION_JS)
|
|
except Exception as exc: # noqa: BLE001
|
|
out["errors"]["chrome"] = _failed(exc)
|
|
try:
|
|
out["content"] = driver.eval(CONTENT_ACTIVATION_JS)
|
|
except Exception as exc: # noqa: BLE001
|
|
out["errors"]["content"] = _failed(exc)
|
|
out["click_ack"] = getattr(driver, "last_click_ack", None)
|
|
if not out["errors"]:
|
|
del out["errors"]
|
|
return out
|
|
|
|
|
|
def click_record(driver: Any, css: Sequence[float]) -> Dict[str, Any]:
|
|
"""The click as asked (CSS pixels) and as the driver sent it (``driver.last_click``: the point, its unit, the device point), as the driver wrote it."""
|
|
return {"css": list(css), "sent": getattr(driver, "last_click", None)}
|
|
|
|
|
|
class Diagnostics:
|
|
"""The record of one browser on one case: its scales and one entry per element."""
|
|
|
|
def __init__(self, case: str, browser: str) -> None:
|
|
self.case, self.browser = case, browser
|
|
self.scales: Optional[Dict[str, Any]] = None
|
|
self.entries: Dict[str, Dict[str, Any]] = {}
|
|
self.save_error: Optional[str] = None
|
|
|
|
def entry(self, name: str) -> Dict[str, Any]:
|
|
return self.entries.setdefault(name, {})
|
|
|
|
def record(self) -> Dict[str, Any]:
|
|
return {"case": self.case, "browser": self.browser, "scales": self.scales, "elements": self.entries}
|
|
|
|
def message(self, headline: str, name: str) -> str:
|
|
"""``headline``, then everything known about the element ``name`` and the scales, as one JSON line a reader can paste."""
|
|
body = {"case": self.case, "browser": self.browser, "element": name, "scales": self.scales, **self.entries.get(name, {})}
|
|
return "%s\n diagnostics: %s" % (headline, json.dumps(body, sort_keys=True))
|
|
|
|
def path(self, environ: Mapping[str, str]) -> Optional[Path]:
|
|
runner = environ.get("RUNNER_TEMP")
|
|
if not runner:
|
|
return None
|
|
return Path(runner) / EVIDENCE_FOLDER / SUBFOLDER / ("%s-%s.json" % (self.case, self.browser))
|
|
|
|
def save(self, environ: Optional[Mapping[str, str]] = None) -> Optional[Path]:
|
|
"""Writes the record where the jobs upload it; None off a runner. A failed write is kept in ``save_error`` and never raised: this runs while a finding may be on its way up."""
|
|
path = self.path(os.environ if environ is None else environ)
|
|
if path is None:
|
|
return None
|
|
try:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(json.dumps(self.record(), indent=1, sort_keys=True) + "\n", encoding="utf-8")
|
|
except OSError as exc:
|
|
self.save_error = _failed(exc)
|
|
return None
|
|
return path
|