Files
feder-cr 5f58bdf808 tests: a field that depends on stock's frame being in-process is recorded, not compared with stock
Stock Playwright's Firefox sets fission.webContentIsolationStrategy=0, so its cross-site frame shares the top's process, and its drag is Juggler's synthetic one (no OLE loop). A field that depends on either is not what stock reads, and the retail capture decides it.

_stock_twin.split_differences splits the differences of a twin by a declared list per twin (a pattern of canonical paths and one of two reasons: in-process frame in stock, synthetic drag in stock); a declared field that differs is recorded (recorded_differences in the report) and a field that is not declared and differs is red.

The drag twin declares the buttons, drag at the source (count and presence), the dragend point less the last drag, and in the frame effectAllowed, dropEffect and mozSourceNode; routing, targets, client points, rel, types, trusted, the input source and the effects of the top document stay compared. The intersection twin has the list and declares nothing yet (moving boundingClientRect is one line).

Red on the old code: the new tests fail at their import of the declared list and of split_differences. unit.all rows: +43 (Linux 4351, Windows 4363).
2026-11-29 16:26:35 +01:00

262 lines
15 KiB
Python

"""What the stock twins share: the same steps on Playwright's own Firefox and on our engine, one browser at a time, and a record of each.
A twin test measures a relation (the dropdown of a select against its element, the drop of a real drag, what an observer reads of a scrolled frame) and its
verdict is "the same as stock Firefox with stock Playwright", never a number of ours: an expected value comes from a capture of retail or from stock in the same job.
HOW STOCK RUNS. The mechanism is the one of the fake web (``scripts/run_fakeweb.py``, ``tests/fakeweb/profile_p2.py::run_on_stock``): the stock Playwright client
(``playwright.sync_api``, imported by name: the fork's guard forbids a static import), ``p.firefox.launch()``, which starts Playwright's own Firefox build that
``python -m playwright install firefox`` put on the runner. That is a row with ``"stock_firefox": true`` of ``ci/required-suites.json``, whose leg the gate gives the
archives, checked against ``ci/py-lock/playwright-browsers.json``. Stock goes FIRST and is closed before ours starts (ci-release-18: one browser at a time). The stock
part runs in a thread of its own (a sync client keeps its loop marked as running in its thread, and ours is a sync client too).
THE SAME WINDOW. Stock is launched HEADED (``headless=False``: a real window, on a display of its own that ``OwnDisplay`` makes the way the wrapper makes ours: ``invisible_core.make_virtual_display()``, an Xvfb of 1920x1080x24 on Linux; on Windows the desktop of the job, a stock client cannot be put on another desktop), as ours is (``launch_case``: the wrapper gives the engine a display of its own, so its windows are real ones; Firefox's ``-headless`` mode is on neither, because popups, drag and drop and window geometry behave differently in it), with the display scale of the case as ``layout.css.devPixelsPerPx`` (the pref ours is launched with for the same case: the scale
is then the one of the page AND of the browser chrome) and a context viewport of the inner size retail reads at that case (``RETAIL_CASES``: the maximized window's
``innerWidth`` x ``innerHeight``). Ours is the maximized window of the same case (``_window_origin.launch_case``).
THE RECORD. Each twin saves, for each browser, what it measured with the scales that could make the two differ: ``scales.page`` (``window.devicePixelRatio`` of the page, its
inner size, ``screen.width/height``: the DECLARED ones of ours) and ``scales.chrome`` read from chrome scope through Marionette (``devicePixelRatio`` of the browser window,
the inner and outer size of the window, and the REAL scale of the screen: ``nsIScreen.contentsScaleFactor`` and ``defaultCSSScaleFactor``, ``windowUtils.displayDPI``). The failure message
prints both records whole. A stock browser that cannot be driven (no Marionette, no dropdown, no drag) is a BROKEN CONTROL: red, and the message says it is no finding about ours.
"""
from __future__ import annotations
import fnmatch
import importlib
import json
import os
import re
import sys
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
from invisible_core import make_virtual_display
from _popup_geometry import in_a_thread_of_its_own
from _window_origin import launch_case, scale_pref
from test_the_maximized_window_frames_and_popups_read_retail_e2e import CASES as RETAIL_CASES
MARIONETTE_ARGS = ["-marionette", "-remote-allow-system-access"]
SCALES_JS = """
const win = Services.wm.getMostRecentWindow("navigator:browser");
const screen = Cc["@mozilla.org/gfx/screenmanager;1"].getService(Ci.nsIScreenManager).primaryScreen;
return JSON.stringify({
chrome_devicePixelRatio: win.devicePixelRatio,
chrome_inner: [win.innerWidth, win.innerHeight],
chrome_outer: [win.outerWidth, win.outerHeight],
real_screen_contentsScaleFactor: screen.contentsScaleFactor,
real_screen_defaultCSSScaleFactor: screen.defaultCSSScaleFactor,
real_displayDPI: win.windowUtils.displayDPI,
});
"""
PAGE_SCALES = """() => ({devicePixelRatio: window.devicePixelRatio, inner: [innerWidth, innerHeight], screen: [screen.width, screen.height]})"""
def on_linux() -> bool:
return sys.platform.startswith("linux")
class OwnDisplay:
"""The display a browser that is not ours is launched on: the wrapper's own mechanism (``make_virtual_display``, what ``InvisiblePlaywright`` starts for ours), never the job's.
On Linux a fresh Xvfb (the core's: 1920x1080x24, access control on, its cookie in ``XAUTHORITY``), one per launch, started before the browser and stopped after it; the browser's environment
gets ``DISPLAY`` and ``XAUTHORITY`` from it and loses the Wayland variables, so a job that runs pytest without ``xvfb-run`` (the rows of the stock twins) still has a screen. On Windows there is
nothing to make: a stock client cannot spawn its browser on another desktop, so it is on the one of the job, and ``environ`` is the environment as it is."""
def __init__(self) -> None:
self._display: Any = None
def __enter__(self) -> "OwnDisplay":
if on_linux():
display = make_virtual_display()
display.start()
self._display = display
return self
def __exit__(self, *exc: Any) -> None:
display, self._display = self._display, None
if display is not None:
display.stop()
def environ(self, base: Optional[Mapping[str, str]] = None) -> Dict[str, str]:
"""``base`` (the process's environment by default) as the browser is launched with it: what the display names set, what it names ``None`` removed."""
env = dict(os.environ if base is None else base)
for name, value in (self._display.launch_env() if self._display is not None else {}).items():
if value is None:
env.pop(name, None)
else:
env[name] = value
return env
class BrokenControl(AssertionError):
"""Stock Firefox could not be driven through the steps: not a finding about ours."""
class Chrome:
"""Chrome scope of the browser below this process, through Marionette (the route of ``test_software_compositing_is_declared_e2e.py``).
``page`` is the page the browser of this launch already opened, and it is required on purpose: ``WebDriver:NewSession`` waits for the end of the browser's start-up, which only a window
ends, and the wrapper launches with ``-silent`` (no window at start-up). A session asked before the first page never gets its answer (the socket times out after 300 s). With the page
as an argument the wrong order cannot be written."""
def __init__(self, page) -> None:
if page is None:
raise TypeError("Chrome needs the page this launch opened first: Marionette's NewSession is answered only once a window exists")
import webfont_probe
self._page = page
self._m = webfont_probe._Marionette(webfont_probe.marionette_active_port())
self._m.call("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {}}})
self._m.call("Marionette:SetContext", {"value": "chrome"})
def script(self, script: str, args: Tuple[Any, ...] = ()) -> Dict[str, Any]:
return json.loads(self._m.call("WebDriver:ExecuteScript", {"script": script, "args": list(args)})["value"])
def scales(self) -> Dict[str, Any]:
"""The record of the scales: the page's (declared) and the chrome's, with the real ones of the screen."""
out = {"page": self._page.evaluate(PAGE_SCALES)}
out.update(self.script(SCALES_JS))
return out
def close(self) -> None:
self._m.close()
def stock_client():
"""The stock Playwright client, imported by name."""
try:
return importlib.import_module("playwright.sync_api").sync_playwright
except ImportError as exc: # a broken environment, not a reason to skip: a skipped gate checks nothing
raise BrokenControl("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc) from exc
def viewport(case: str) -> Dict[str, int]:
"""The inner size retail reads for the maximized window of ``case``, CSS pixels."""
maximized = RETAIL_CASES[case]["maximized"]
return {"width": int(maximized["iw"]), "height": int(maximized["ih"])}
def stock_user_prefs(case: str) -> Dict[str, Any]:
"""The user prefs stock Playwright's Firefox is launched with for ``case``: the display scale as the STRING ours is launched with (``scale_pref``), and a free Marionette port.
A number would be set with ``setIntPref`` by the Juggler of Playwright's build, and ``layout.css.devPixelsPerPx`` is a string pref: ``Browser.enable`` fails and no case launches."""
return {"layout.css.devPixelsPerPx": scale_pref(case), "marionette.port": 0}
def _on_stock(case: str, measure: Callable[[Any, Chrome], Dict[str, Any]]) -> Dict[str, Any]:
def run() -> Dict[str, Any]:
sync_playwright = stock_client()
with sync_playwright() as p, OwnDisplay() as display:
browser = p.firefox.launch(headless=False, args=MARIONETTE_ARGS, env=display.environ(),
firefox_user_prefs=stock_user_prefs(case))
chrome = None
try:
page = browser.new_context(viewport=viewport(case)).new_page()
chrome = Chrome(page)
return measure(page, chrome)
finally:
if chrome is not None:
chrome.close()
browser.close()
try:
return in_a_thread_of_its_own(run)
except BrokenControl:
raise
except Exception as exc:
raise BrokenControl("BROKEN CONTROL, no finding about ours: stock Firefox (Playwright's own build) could not be driven through the steps of %s: %s: %s"
% (case, type(exc).__name__, exc)) from exc
def _on_ours(case: str, firefox_binary: str, measure: Callable[[Any, Chrome], Dict[str, Any]]) -> Dict[str, Any]:
with launch_case(firefox_binary, case, extra_args=MARIONETTE_ARGS, extra_prefs={"marionette.port": 0}) as browser:
page = browser.new_page() # first: the window the session below waits for
chrome = Chrome(page)
try:
return measure(page, chrome)
finally:
chrome.close()
def run_twin(case: str, firefox_binary: str, measure: Callable[[Any, Chrome], Dict[str, Any]]) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""(stock's record, ours): the same ``measure(page, chrome)`` on Playwright's own Firefox first and on our engine second. Needs MOZ_REMOTE_ALLOW_SYSTEM_ACCESS=1."""
stock = _on_stock(case, measure)
ours = _on_ours(case, firefox_binary, measure)
return stock, ours
def both(case: str, stock: Dict[str, Any], ours: Dict[str, Any], reference: str = "stock") -> str:
"""The two records whole, for the message of a red twin (``reference`` names the first: stock, or retail)."""
return "\n case %s\n %s: %s\n ours: %s" % (case, reference, json.dumps(stock, sort_keys=True), json.dumps(ours, sort_keys=True))
def differences(stock: Any, ours: Any, tolerances: Dict[str, float] = None, path: str = "") -> List[str]:
"""Every place where the two records differ, as ``path: stock X, ours Y``. A number differs by more than the tolerance of its key (the last name of its path; 0 when none);
everything else must be equal."""
tolerances = tolerances or {}
out: List[str] = []
if isinstance(stock, dict) and isinstance(ours, dict):
for key in sorted(set(stock) | set(ours)):
if key not in stock or key not in ours:
out.append("%s.%s: only %s has it" % (path, key, "stock" if key in stock else "ours"))
else:
out += differences(stock[key], ours[key], tolerances, "%s.%s" % (path, key))
elif isinstance(stock, list) and isinstance(ours, list) and len(stock) == len(ours):
for i, (a, b) in enumerate(zip(stock, ours)):
out += differences(a, b, tolerances, "%s[%d]" % (path, i))
elif isinstance(stock, (int, float)) and isinstance(ours, (int, float)) and not isinstance(stock, bool) and not isinstance(ours, bool):
tolerance = tolerances.get(path.rsplit(".", 1)[-1].split("[", 1)[0], 0.0)
if abs(stock - ours) > tolerance:
out.append("%s: stock %r, ours %r (tolerance %r)" % (path, stock, ours, tolerance))
elif stock != ours:
out.append("%s: stock %r, ours %r" % (path, stock, ours))
return out
#: The two reasons a field of a stock twin's record can be left out of the comparison with stock (the retail capture of the case decides it instead).
IN_PROCESS_FRAME = "in-process frame in stock"
SYNTHETIC_DRAG = "synthetic drag in stock"
REASONS = {
IN_PROCESS_FRAME: "stock Playwright's Firefox sets fission.webContentIsolationStrategy=0, so its cross-site frame shares the top's process and ours is in another process: a field that depends on "
"the frame being in another process is not what stock reads",
SYNTHETIC_DRAG: "stock's drag is Juggler's synthetic one: no OLE drag loop, so no timer-driven drag event and no buttons held, and nothing a real drag has beyond the events themselves",
}
def canonical(path: str, root: str) -> str:
"""``path`` of a difference less its root, with every list index as ``[]``: ``drag drop.top.once[3].buttons`` is ``top.once[].buttons`` for the root ``drag drop``."""
rest = path[len(root):].lstrip(".") if path.startswith(root) else path
return re.sub(r"\[\d+\]", "[]", rest)
def leaf_paths(node: Any, prefix: str = "") -> List[str]:
"""The canonical path of every leaf of a record (what a declared field has to name to exist in it)."""
if isinstance(node, dict):
return [p for k, v in node.items() for p in leaf_paths(v, "%s.%s" % (prefix, k) if prefix else str(k))] or [prefix]
if isinstance(node, list):
return [p for v in node for p in leaf_paths(v, prefix + "[]")] or [prefix + "[]"]
return [prefix]
def stale_entries(declared: Mapping[str, str], *records: Any) -> List[str]:
"""The declared fields (a pattern of canonical paths, ``*`` for any run of characters) that name nothing in any of ``records``, and the reasons that are not one of ``REASONS``."""
paths = [p for record in records for p in leaf_paths(record)]
out = ["%s names no field of the record" % field for field in declared if not any(fnmatch.fnmatchcase(p, field) for p in paths)]
return out + ["%s has the reason %r, which is not one of %s" % (field, why, sorted(REASONS)) for field, why in declared.items() if why not in REASONS]
def split_differences(stock: Any, ours: Any, declared: Mapping[str, str], tolerances: Dict[str, float] = None, path: str = "") -> Tuple[List[str], List[str]]:
"""``(red, recorded)``: the differences of ``differences`` split by the declared list of the twin. A difference at a declared field is recorded (with its reason, for the report) and does not
decide the verdict; every other one is red. ``declared`` maps a pattern of canonical paths (``canonical``) to one of ``REASONS``."""
red: List[str] = []
recorded: List[str] = []
for difference in differences(stock, ours, tolerances, path):
where = canonical(difference.split(": ", 1)[0], path)
why = next((reason for field, reason in declared.items() if fnmatch.fnmatchcase(where, field)), None)
if why is None:
red.append(difference)
else:
recorded.append("%s [recorded, not compared: %s]" % (difference, why))
return red, recorded