e2e: three new test files stored with LF, as the index of the repository has them (they were committed with CRLF)

This commit is contained in:
feder-cr committed 2026-11-28 02:40:48 +01:00
1 parent 310b88e81d
commit 678978399c
3 files changed
+526 -526

No files matched your search

@@ -1,176 +1,176 @@
"""The dropdown of a ``<select>`` opens on the real screen at the element the page showed, in the top document and in a frame of another site.
THIS IS A PRODUCT MEASUREMENT, NOT A PAGE-VISIBLE ONE. A page cannot read where a dropdown opens. But the engine declares to the content process the window origin and the
chrome offset the page reads (not the host's), and the chrome actors of the browser that anchor a popup on screen (the select dropdown, the autocomplete list, the pickers,
the form validation bubble) compute their anchor in the content process with ``windowUtils.getElementBoundingScreenRect``: the declared window origin plus the box of the
element. The parent then opens the popup at those numbers, on the REAL screen. Unless the parent maps the declared point back to the real one, the dropdown opens away
from its element by the difference between the declared window and the real one, and a person who uses the browser sees it (and, in a frame of another process, by the
declared chrome offset too: the matrix of that process).
What it does, per display case (the four of the window tests): the browser is launched with Marionette (``-marionette -remote-allow-system-access``, the route of
``test_software_compositing_is_declared_e2e.py``), so the test can read the chrome of the browser. A page of the top site has a ``<select>`` (160x28 at (30, 20)) and a frame
of another site, 420x200 at (30, 120), with the same ``<select>`` at (40, 20) of its document. For each of the two selects:
* the client's own click (``locator.click``, the mouse the client sends) opens the dropdown, and the test waits for the menulist popup of ``ContentSelectDropdown`` to be ``open``;
* from chrome, two rectangles are read, in the CSS pixels of the chrome: the popup's real screen rectangle (``popup.getOuterScreenRect()``, the bounds of the popup's
own widget) and the select's REAL screen rectangle, computed in the parent from the real geometry of the browser: the content-area rectangle of the ``<browser>`` plus
the select's rectangle in the page (the page's own ``getBoundingClientRect``, plus the frame's box for the second one), converted with the chrome window's
``windowUtils.toScreenRectInCSSUnits`` (the widget of the window as it really is);
* the popup is anchored below the element: its left is the element's left and its top is the element's bottom, each within ONE device pixel (``1 / devicePixelRatio`` CSS
pixels of the chrome window), and the frame's popup is anchored as the top one is (offset to the element within one device pixel of the top's offset), so a CSS margin of the
popup, if the build has one, is not mistaken for a displacement.
RED WITHOUT THE MAP OF THE POPUPS (design §3). Once the content process is told the declared window origin and the declared chrome offset, ``getElementBoundingScreenRect``
answers declared screen coordinates, and ``SelectParent`` opens the popup at them. The real window is not at the declared place (on Windows the real chrome has other
heights; on Linux the window manager's frame and the host's chrome are not retail's), so the popup lands at the real screen rectangle shifted by (declared - real) and its left
or top is more than a device pixel from the element's. With the map, ``p_real = p_decl - (W_decl - W_real) - d`` in the parent, the two rectangles agree. This test is what shows
the shift in the top document (the window origin) and in the frame (the window origin and the matrix).
The autocomplete popup is not measured: it needs a form-history entry written to the profile from chrome and a typed field, and nothing in this suite says that the engine
keeps form history on; a test that skips there is red in the verdict.
The engine that answers these values is not released yet: this test is red on an engine that declares the window origin without the map, on purpose. It enters the suite with it.
"""
from __future__ import annotations
import json
import time
from typing import Any, Dict, Tuple
import pytest
from _fission_frames import Sites, wait_frame
from _window_origin import CASES, DEADLINE_S, launch_case, wait_for
pytestmark = pytest.mark.e2e
MARIONETTE_ARGS = ["-marionette", "-remote-allow-system-access"]
TOP = """<!doctype html><meta charset=utf-8><title>select</title>
<style>html,body{margin:0;padding:0}
select{position:absolute;box-sizing:border-box;width:160px;height:28px;margin:0}
#s{left:30px;top:20px}#f{position:absolute;left:30px;top:120px;width:420px;height:200px;border:0}</style>
<body><select id=s><option>one</option><option>two</option><option>three</option></select><iframe id=f src="%s"></iframe>"""
FRAME = """<!doctype html><meta charset=utf-8><title>select in a frame</title>
<style>html,body{margin:0;padding:0}select{position:absolute;box-sizing:border-box;width:160px;height:28px;margin:0;left:40px;top:20px}</style>
<body><select id=s><option>one</option><option>two</option><option>three</option></select>"""
#: The select's rectangle in the page's own viewport, CSS pixels.
SELECT_BOX = "() => { const r = document.getElementById('s').getBoundingClientRect(); return {x: r.left, y: r.top, w: r.width, h: r.height}; }"
FRAME_BOX = "() => { const r = document.getElementById('f').getBoundingClientRect(); return {x: r.left, y: r.top}; }"
# The reads of the browser chrome, in the script of Marionette (chrome scope).
POPUP_STATE_JS = """
const win = Services.wm.getMostRecentWindow("navigator:browser");
const popup = win.document.querySelector("#ContentSelectDropdown > menupopup");
return JSON.stringify({state: popup ? popup.state : "no popup"});
"""
MEASURE_JS = """
const [rect] = arguments;
const win = Services.wm.getMostRecentWindow("navigator:browser");
const popup = win.document.querySelector("#ContentSelectDropdown > menupopup");
const browser = win.gBrowser.selectedBrowser;
const b = browser.getBoundingClientRect();
const el = win.windowUtils.toScreenRectInCSSUnits(b.left + rect.x, b.top + rect.y, rect.w, rect.h);
const p = popup.getOuterScreenRect();
const plain = r => ({left: r.left, top: r.top, right: r.right, bottom: r.bottom});
return JSON.stringify({state: popup.state, element: plain(el), popup: plain(p), dpr: win.devicePixelRatio});
"""
CLOSE_JS = """
const win = Services.wm.getMostRecentWindow("navigator:browser");
const popup = win.document.querySelector("#ContentSelectDropdown > menupopup");
popup.hidePopup();
return JSON.stringify({state: popup.state});
"""
def _marionette():
import webfont_probe
m = webfont_probe._Marionette(webfont_probe.marionette_active_port())
m.call("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {}}})
m.call("Marionette:SetContext", {"value": "chrome"})
return m
def _script(marionette, script: str, args=()) -> Dict[str, Any]:
return json.loads(marionette.call("WebDriver:ExecuteScript", {"script": script, "args": list(args)})["value"])
def _wait_state(page, marionette, state: str) -> Dict[str, Any]:
"""The popup's state once it is ``state`` (open or closed), polled; the last reading at the deadline."""
seen: Dict[str, Any] = {}
def look() -> bool:
seen.update(_script(marionette, POPUP_STATE_JS))
return seen["state"] == state
wait_for(page, look, DEADLINE_S)
return seen
def _measure(page, marionette, rect: Dict[str, float]) -> Dict[str, Any]:
"""Opens nothing: reads the open popup and the select's real screen rectangle, both in CSS pixels of the chrome."""
read = _script(marionette, MEASURE_JS, [rect])
# the popup's widget may still be sizing itself: read until two looks agree
end = time.monotonic() + DEADLINE_S
while True:
page.wait_for_timeout(100)
again = _script(marionette, MEASURE_JS, [rect])
if again == read or time.monotonic() >= end:
return again
read = again
def _anchor_offset(read: Dict[str, Any]) -> Tuple[float, float]:
"""(popup left - element left, popup top - element bottom), CSS pixels of the chrome."""
return (read["popup"]["left"] - read["element"]["left"], read["popup"]["top"] - read["element"]["bottom"])
@pytest.mark.parametrize("case", sorted(CASES))
def test_a_select_dropdown_opens_at_its_element(firefox_binary, monkeypatch, case):
monkeypatch.setenv("MOZ_REMOTE_ALLOW_SYSTEM_ACCESS", "1") # the chrome-scope reads below
marionette = None
reads: Dict[str, Dict[str, Any]] = {}
with Sites() as sites:
sites.route("A", "/page", lambda handler: TOP % sites.url("B", "/select"))
sites.route("B", "/select", FRAME)
try:
with launch_case(firefox_binary, case, extra_args=MARIONETTE_ARGS, extra_prefs={"marionette.port": 0}) as browser:
page = browser.new_page()
page.goto(sites.url("A", "/page"), wait_until="load", timeout=30000)
frame = wait_frame(page, sites.origin["B"], "/select", seconds=DEADLINE_S)
wait_for(page, lambda: frame.evaluate("() => document.readyState") == "complete")
marionette = _marionette()
top_rect = page.evaluate(SELECT_BOX)
frame_origin = page.evaluate(FRAME_BOX)
in_frame = frame.evaluate(SELECT_BOX)
frame_rect = {"x": frame_origin["x"] + in_frame["x"], "y": frame_origin["y"] + in_frame["y"], "w": in_frame["w"], "h": in_frame["h"]}
for name, document, rect in (("top", page, top_rect), ("frame", frame, frame_rect)):
document.locator("#s").click()
opened = _wait_state(page, marionette, "open")
assert opened["state"] == "open", "%s, %s document: the dropdown did not open after a click on the select (popup state %r)" % (case, name, opened)
reads[name] = _measure(page, marionette, rect)
_script(marionette, CLOSE_JS)
closed = _wait_state(page, marionette, "closed")
assert closed["state"] == "closed", "%s, %s document: the dropdown did not close (popup state %r)" % (case, name, closed)
finally:
if marionette is not None:
marionette.close()
for name, read in reads.items():
tolerance = 1.0 / read["dpr"] + 0.01
left, top = _anchor_offset(read)
assert abs(left) <= tolerance and abs(top) <= tolerance, (
"%s, %s document: the dropdown opened at (left %r, top %r) on the real screen and the select's real rectangle is %r: left is off by %r and top (against the "
"element's bottom) by %r CSS pixels of the chrome, one device pixel is %r (the popup is %r)"
% (case, name, read["popup"]["left"], read["popup"]["top"], read["element"], left, top, tolerance, read["popup"]))
top_offset, frame_offset = _anchor_offset(reads["top"]), _anchor_offset(reads["frame"])
tolerance = 1.0 / reads["top"]["dpr"] + 0.01
assert abs(frame_offset[0] - top_offset[0]) <= tolerance and abs(frame_offset[1] - top_offset[1]) <= tolerance, (
"%s: the dropdown of the select in the frame is anchored %r from its element, the one of the top document %r: a frame of another process is shifted from the top by %r"
% (case, frame_offset, top_offset, (frame_offset[0] - top_offset[0], frame_offset[1] - top_offset[1])))
"""The dropdown of a ``<select>`` opens on the real screen at the element the page showed, in the top document and in a frame of another site.
THIS IS A PRODUCT MEASUREMENT, NOT A PAGE-VISIBLE ONE. A page cannot read where a dropdown opens. But the engine declares to the content process the window origin and the
chrome offset the page reads (not the host's), and the chrome actors of the browser that anchor a popup on screen (the select dropdown, the autocomplete list, the pickers,
the form validation bubble) compute their anchor in the content process with ``windowUtils.getElementBoundingScreenRect``: the declared window origin plus the box of the
element. The parent then opens the popup at those numbers, on the REAL screen. Unless the parent maps the declared point back to the real one, the dropdown opens away
from its element by the difference between the declared window and the real one, and a person who uses the browser sees it (and, in a frame of another process, by the
declared chrome offset too: the matrix of that process).
What it does, per display case (the four of the window tests): the browser is launched with Marionette (``-marionette -remote-allow-system-access``, the route of
``test_software_compositing_is_declared_e2e.py``), so the test can read the chrome of the browser. A page of the top site has a ``<select>`` (160x28 at (30, 20)) and a frame
of another site, 420x200 at (30, 120), with the same ``<select>`` at (40, 20) of its document. For each of the two selects:
* the client's own click (``locator.click``, the mouse the client sends) opens the dropdown, and the test waits for the menulist popup of ``ContentSelectDropdown`` to be ``open``;
* from chrome, two rectangles are read, in the CSS pixels of the chrome: the popup's real screen rectangle (``popup.getOuterScreenRect()``, the bounds of the popup's
own widget) and the select's REAL screen rectangle, computed in the parent from the real geometry of the browser: the content-area rectangle of the ``<browser>`` plus
the select's rectangle in the page (the page's own ``getBoundingClientRect``, plus the frame's box for the second one), converted with the chrome window's
``windowUtils.toScreenRectInCSSUnits`` (the widget of the window as it really is);
* the popup is anchored below the element: its left is the element's left and its top is the element's bottom, each within ONE device pixel (``1 / devicePixelRatio`` CSS
pixels of the chrome window), and the frame's popup is anchored as the top one is (offset to the element within one device pixel of the top's offset), so a CSS margin of the
popup, if the build has one, is not mistaken for a displacement.
RED WITHOUT THE MAP OF THE POPUPS (design §3). Once the content process is told the declared window origin and the declared chrome offset, ``getElementBoundingScreenRect``
answers declared screen coordinates, and ``SelectParent`` opens the popup at them. The real window is not at the declared place (on Windows the real chrome has other
heights; on Linux the window manager's frame and the host's chrome are not retail's), so the popup lands at the real screen rectangle shifted by (declared - real) and its left
or top is more than a device pixel from the element's. With the map, ``p_real = p_decl - (W_decl - W_real) - d`` in the parent, the two rectangles agree. This test is what shows
the shift in the top document (the window origin) and in the frame (the window origin and the matrix).
The autocomplete popup is not measured: it needs a form-history entry written to the profile from chrome and a typed field, and nothing in this suite says that the engine
keeps form history on; a test that skips there is red in the verdict.
The engine that answers these values is not released yet: this test is red on an engine that declares the window origin without the map, on purpose. It enters the suite with it.
"""
from __future__ import annotations
import json
import time
from typing import Any, Dict, Tuple
import pytest
from _fission_frames import Sites, wait_frame
from _window_origin import CASES, DEADLINE_S, launch_case, wait_for
pytestmark = pytest.mark.e2e
MARIONETTE_ARGS = ["-marionette", "-remote-allow-system-access"]
TOP = """<!doctype html><meta charset=utf-8><title>select</title>
<style>html,body{margin:0;padding:0}
select{position:absolute;box-sizing:border-box;width:160px;height:28px;margin:0}
#s{left:30px;top:20px}#f{position:absolute;left:30px;top:120px;width:420px;height:200px;border:0}</style>
<body><select id=s><option>one</option><option>two</option><option>three</option></select><iframe id=f src="%s"></iframe>"""
FRAME = """<!doctype html><meta charset=utf-8><title>select in a frame</title>
<style>html,body{margin:0;padding:0}select{position:absolute;box-sizing:border-box;width:160px;height:28px;margin:0;left:40px;top:20px}</style>
<body><select id=s><option>one</option><option>two</option><option>three</option></select>"""
#: The select's rectangle in the page's own viewport, CSS pixels.
SELECT_BOX = "() => { const r = document.getElementById('s').getBoundingClientRect(); return {x: r.left, y: r.top, w: r.width, h: r.height}; }"
FRAME_BOX = "() => { const r = document.getElementById('f').getBoundingClientRect(); return {x: r.left, y: r.top}; }"
# The reads of the browser chrome, in the script of Marionette (chrome scope).
POPUP_STATE_JS = """
const win = Services.wm.getMostRecentWindow("navigator:browser");
const popup = win.document.querySelector("#ContentSelectDropdown > menupopup");
return JSON.stringify({state: popup ? popup.state : "no popup"});
"""
MEASURE_JS = """
const [rect] = arguments;
const win = Services.wm.getMostRecentWindow("navigator:browser");
const popup = win.document.querySelector("#ContentSelectDropdown > menupopup");
const browser = win.gBrowser.selectedBrowser;
const b = browser.getBoundingClientRect();
const el = win.windowUtils.toScreenRectInCSSUnits(b.left + rect.x, b.top + rect.y, rect.w, rect.h);
const p = popup.getOuterScreenRect();
const plain = r => ({left: r.left, top: r.top, right: r.right, bottom: r.bottom});
return JSON.stringify({state: popup.state, element: plain(el), popup: plain(p), dpr: win.devicePixelRatio});
"""
CLOSE_JS = """
const win = Services.wm.getMostRecentWindow("navigator:browser");
const popup = win.document.querySelector("#ContentSelectDropdown > menupopup");
popup.hidePopup();
return JSON.stringify({state: popup.state});
"""
def _marionette():
import webfont_probe
m = webfont_probe._Marionette(webfont_probe.marionette_active_port())
m.call("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {}}})
m.call("Marionette:SetContext", {"value": "chrome"})
return m
def _script(marionette, script: str, args=()) -> Dict[str, Any]:
return json.loads(marionette.call("WebDriver:ExecuteScript", {"script": script, "args": list(args)})["value"])
def _wait_state(page, marionette, state: str) -> Dict[str, Any]:
"""The popup's state once it is ``state`` (open or closed), polled; the last reading at the deadline."""
seen: Dict[str, Any] = {}
def look() -> bool:
seen.update(_script(marionette, POPUP_STATE_JS))
return seen["state"] == state
wait_for(page, look, DEADLINE_S)
return seen
def _measure(page, marionette, rect: Dict[str, float]) -> Dict[str, Any]:
"""Opens nothing: reads the open popup and the select's real screen rectangle, both in CSS pixels of the chrome."""
read = _script(marionette, MEASURE_JS, [rect])
# the popup's widget may still be sizing itself: read until two looks agree
end = time.monotonic() + DEADLINE_S
while True:
page.wait_for_timeout(100)
again = _script(marionette, MEASURE_JS, [rect])
if again == read or time.monotonic() >= end:
return again
read = again
def _anchor_offset(read: Dict[str, Any]) -> Tuple[float, float]:
"""(popup left - element left, popup top - element bottom), CSS pixels of the chrome."""
return (read["popup"]["left"] - read["element"]["left"], read["popup"]["top"] - read["element"]["bottom"])
@pytest.mark.parametrize("case", sorted(CASES))
def test_a_select_dropdown_opens_at_its_element(firefox_binary, monkeypatch, case):
monkeypatch.setenv("MOZ_REMOTE_ALLOW_SYSTEM_ACCESS", "1") # the chrome-scope reads below
marionette = None
reads: Dict[str, Dict[str, Any]] = {}
with Sites() as sites:
sites.route("A", "/page", lambda handler: TOP % sites.url("B", "/select"))
sites.route("B", "/select", FRAME)
try:
with launch_case(firefox_binary, case, extra_args=MARIONETTE_ARGS, extra_prefs={"marionette.port": 0}) as browser:
page = browser.new_page()
page.goto(sites.url("A", "/page"), wait_until="load", timeout=30000)
frame = wait_frame(page, sites.origin["B"], "/select", seconds=DEADLINE_S)
wait_for(page, lambda: frame.evaluate("() => document.readyState") == "complete")
marionette = _marionette()
top_rect = page.evaluate(SELECT_BOX)
frame_origin = page.evaluate(FRAME_BOX)
in_frame = frame.evaluate(SELECT_BOX)
frame_rect = {"x": frame_origin["x"] + in_frame["x"], "y": frame_origin["y"] + in_frame["y"], "w": in_frame["w"], "h": in_frame["h"]}
for name, document, rect in (("top", page, top_rect), ("frame", frame, frame_rect)):
document.locator("#s").click()
opened = _wait_state(page, marionette, "open")
assert opened["state"] == "open", "%s, %s document: the dropdown did not open after a click on the select (popup state %r)" % (case, name, opened)
reads[name] = _measure(page, marionette, rect)
_script(marionette, CLOSE_JS)
closed = _wait_state(page, marionette, "closed")
assert closed["state"] == "closed", "%s, %s document: the dropdown did not close (popup state %r)" % (case, name, closed)
finally:
if marionette is not None:
marionette.close()
for name, read in reads.items():
tolerance = 1.0 / read["dpr"] + 0.01
left, top = _anchor_offset(read)
assert abs(left) <= tolerance and abs(top) <= tolerance, (
"%s, %s document: the dropdown opened at (left %r, top %r) on the real screen and the select's real rectangle is %r: left is off by %r and top (against the "
"element's bottom) by %r CSS pixels of the chrome, one device pixel is %r (the popup is %r)"
% (case, name, read["popup"]["left"], read["popup"]["top"], read["element"], left, top, tolerance, read["popup"]))
top_offset, frame_offset = _anchor_offset(reads["top"]), _anchor_offset(reads["frame"])
tolerance = 1.0 / reads["top"]["dpr"] + 0.01
assert abs(frame_offset[0] - top_offset[0]) <= tolerance and abs(frame_offset[1] - top_offset[1]) <= tolerance, (
"%s: the dropdown of the select in the frame is anchored %r from its element, the one of the top document %r: a frame of another process is shifted from the top by %r"
% (case, frame_offset, top_offset, (frame_offset[0] - top_offset[0], frame_offset[1] - top_offset[1])))
@@ -1,162 +1,162 @@
"""Click, hover, drag and wheel reach the element under the cursor, in the top document and in a frame of another site, at every display scale.
The parent turns a point of the window into a point of the content with the matrix it keeps of each content process (``mChildToParentConversionMatrix``), and the
mouse, the wheel and the drag go through it. The matrix the parent SENDS to the child is a different one (it carries the window origin the page reads), and a change
there must not move the input: the point the parent hit-tests, the element the event is dispatched at and the ``clientX/Y`` it carries must stay the cursor's.
Playwright's own input (``page.mouse``) is what a client sends, so this is what a script sees break.
What it does, per display case (the four of the window tests), once for the top document and once for a frame of another site, 500x240 at (20, 200) of the same
page, both holding the same four boxes (CSS pixels of the document): a button ``click`` (60x40 at (20, 20)), a box ``hover`` (60x40 at (100, 20)), a box ``drag``
(140x90 at (180, 20)) and a scroller ``scroll`` (140x100 at (20, 80), 600 high inside). The mouse is the client's (``page.mouse``), the point is the box's own
centre plus the document's origin in the page:
* click: ``mouse.click`` at the centre of ``click``: the document hears trusted ``mousedown``, ``mouseup`` and ``click`` AT ``click``, with ``clientX/Y`` at the point
EXACTLY (no tolerance; every requested point is a whole CSS pixel);
* hover: ``mouse.move`` to the centre of ``hover``: ``mouseover`` is dispatched at ``hover``, at the exact point, and the element matches ``:hover``;
* drag: ``mousedown`` at the centre of ``drag``, six moves to a point 30 right and 20 below, ``mouseup``: ``mousedown`` and ``mouseup`` AT ``drag`` with the two points,
the ``mousemove`` events with the left button held and the last at the end point;
* wheel: ``mouse.wheel(0, 120)`` over the centre of ``scroll``: the document hears a trusted ``wheel`` at ``scroll``, at the exact point, and ``scroll.scrollTop`` grows.
The existing suites that read input in a frame of another site and are in the candidate's rows already: ``test_nested_frame_actions.py`` (a click, and a pointer at a large
offset, with the scales 1, 1.25, 1.5 and 2, in one-, two- and three-process pages, and the wheel at scales 1 and 1.25 under a zoom),
``test_a_click_in_an_iframe_lands_at_the_frames_own_screen_origin_e2e.py`` (one click), ``test_fission_frames_tree_input_and_pixels_e2e.py`` (clicks under a transform, after a
scroll, typing), ``test_a_drag_keeps_its_buttons_pressed_e2e.py`` and ``test_drag_motion.py`` (a drag in the top document), ``test_input_is_born_before_the_page_sees_it_e2e.py``
(keys and moves). None puts the four kinds of input in both documents at the four scales: this file does, and only this.
The engine that answers these values is not released yet: it must pass on the engine of the pin, where the matrix is the real one; it is red if the matrix the
parent sends moves the input.
"""
from __future__ import annotations
from typing import Any, Dict, List, Tuple
import pytest
from _fission_frames import Sites, wait_frame
from _window_origin import CASES, DEADLINE_S, launch_case, wait_for
pytestmark = pytest.mark.e2e
#: The boxes' centres in the document, CSS pixels.
CLICK, HOVER, DRAG, SCROLL = (50, 40), (130, 40), (250, 65), (90, 130)
DRAG_TO = (280, 85)
#: The frame's place in the top document.
FRAME_AT = (20, 200)
BODY = """<style>html,body{margin:0;padding:0}.b{position:absolute;box-sizing:border-box;margin:0;padding:0}
#click{left:20px;top:20px;width:60px;height:40px}#hover{left:100px;top:20px;width:60px;height:40px;background:#eee}
#drag{left:180px;top:20px;width:140px;height:90px;background:#9bd}
#scroll{left:20px;top:80px;width:140px;height:100px;overflow:auto;background:#bd9}#scroll div{height:600px}</style>
<button id=click class=b>click</button><div id=hover class=b>hover</div><div id=drag class=b>drag</div><div id=scroll class=b><div></div></div>
<script>
window.__ev = [];
const idOf = e => { const n = e.target.closest ? e.target.closest('[id]') : null; return n ? n.id : null; };
for (const t of ['click', 'mouseover', 'mousedown', 'mousemove', 'mouseup', 'wheel'])
document.addEventListener(t, e => { window.__ev.push({t: t, id: idOf(e), cx: e.clientX, cy: e.clientY, trusted: e.isTrusted, buttons: e.buttons}); }, true);
</script>"""
TOP = ("<!doctype html><meta charset=utf-8><title>input</title><style>#f{position:absolute;left:20px;top:200px;width:500px;height:240px;border:0}</style>"
+ BODY + '<iframe id=f src="%s"></iframe>')
FRAME = "<!doctype html><meta charset=utf-8><title>input frame</title>" + BODY
def _events(doc) -> List[Dict[str, Any]]:
return doc.evaluate("() => window.__ev")
def _where(case: str, doc_name: str, what: str, events: List[Dict[str, Any]]) -> str:
return "%s, %s document, %s: events heard %r" % (case, doc_name, what, events)
def _at(event: Dict[str, Any], point: Tuple[float, float], case: str) -> bool:
"""Exactly the requested point: no tolerance. Every requested point is a whole CSS pixel (the boxes' centres and the frame's origin are), so the event's
``clientX/Y`` of the document is that value at every scale."""
return (event["cx"], event["cy"]) == (point[0], point[1])
def _said(case: str, event: Dict[str, Any], point: Tuple[float, float]) -> str:
dpr = CASES[case][0]
return "requested point %r, received (%r, %r), scale %r" % (point, event["cx"], event["cy"], dpr)
def _of(events: List[Dict[str, Any]], kind: str, box: str) -> List[Dict[str, Any]]:
return [e for e in events if e["t"] == kind and e["id"] == box]
def _fresh(doc) -> None:
doc.evaluate("() => { window.__ev.length = 0; }")
def _check_click(page, doc, origin, case, name) -> None:
_fresh(doc)
page.mouse.click(origin[0] + CLICK[0], origin[1] + CLICK[1])
wait_for(page, lambda: _of(_events(doc), "click", "click"))
events = _events(doc)
where = _where(case, name, "click at %r" % (CLICK,), events)
for kind in ("mousedown", "mouseup", "click"):
heard = _of(events, kind, "click")
assert heard, "%s; no trusted %s at 'click'" % (where, kind)
assert heard[-1]["trusted"], "%s; %s is not trusted" % (where, kind)
assert _at(heard[-1], CLICK, case), "%s; %s is not at the point: %s" % (where, kind, _said(case, heard[-1], CLICK))
def _check_hover(page, doc, origin, case, name) -> None:
_fresh(doc)
page.mouse.move(origin[0] + HOVER[0], origin[1] + HOVER[1])
wait_for(page, lambda: _of(_events(doc), "mouseover", "hover"))
where = _where(case, name, "hover at %r" % (HOVER,), _events(doc))
over = _of(_events(doc), "mouseover", "hover")
assert over and over[-1]["trusted"], "%s; no trusted mouseover at 'hover'" % where
assert wait_for(page, lambda: doc.evaluate("() => document.getElementById('hover').matches(':hover')")), "%s; 'hover' does not match :hover" % where
moves = [e for e in _events(doc) if e["t"] == "mousemove"]
assert moves, "%s; no mousemove" % where
assert _at(moves[-1], HOVER, case), "%s; the last mousemove is not at the point: %s" % (where, _said(case, moves[-1], HOVER))
def _check_drag(page, doc, origin, case, name) -> None:
_fresh(doc)
page.mouse.move(origin[0] + DRAG[0], origin[1] + DRAG[1])
page.mouse.down()
page.mouse.move(origin[0] + DRAG_TO[0], origin[1] + DRAG_TO[1], steps=6)
page.mouse.up()
wait_for(page, lambda: _of(_events(doc), "mouseup", "drag"))
events = _events(doc)
where = _where(case, name, "drag from %r to %r" % (DRAG, DRAG_TO), events)
down, up = _of(events, "mousedown", "drag"), _of(events, "mouseup", "drag")
assert down and up, "%s; no mousedown or no mouseup at 'drag'" % where
assert _at(down[-1], DRAG, case), "%s; mousedown at 'drag' is not at the start point: %s" % (where, _said(case, down[-1], DRAG))
assert _at(up[-1], DRAG_TO, case), "%s; mouseup at 'drag' is not at the end point: %s" % (where, _said(case, up[-1], DRAG_TO))
held = [e for e in events if e["t"] == "mousemove" and e["buttons"] == 1]
assert held, "%s; no mousemove with the left button held" % where
assert _at(held[-1], DRAG_TO, case), "%s; the last mousemove with the left button held is not at the end point: %s" % (where, _said(case, held[-1], DRAG_TO))
def _check_wheel(page, doc, origin, case, name) -> None:
_fresh(doc)
page.mouse.move(origin[0] + SCROLL[0], origin[1] + SCROLL[1])
page.mouse.wheel(0, 120)
wait_for(page, lambda: doc.evaluate("() => document.getElementById('scroll').scrollTop") > 0 and _of(_events(doc), "wheel", "scroll"))
events = _events(doc)
where = _where(case, name, "wheel over %r" % (SCROLL,), events)
wheel = _of(events, "wheel", "scroll")
assert wheel and wheel[-1]["trusted"], "%s; no trusted wheel at 'scroll'" % where
assert _at(wheel[-1], SCROLL, case), "%s; the wheel is not at the point: %s" % (where, _said(case, wheel[-1], SCROLL))
assert doc.evaluate("() => document.getElementById('scroll').scrollTop") > 0, "%s; the scroller did not scroll" % where
@pytest.mark.parametrize("case", sorted(CASES))
def test_input_reaches_the_top_and_a_frame_of_another_site(firefox_binary, case):
with Sites() as sites:
sites.route("A", "/page", lambda handler: TOP % sites.url("B", "/input"))
sites.route("B", "/input", FRAME)
with launch_case(firefox_binary, case) as browser:
page = browser.new_page()
page.goto(sites.url("A", "/page"), wait_until="load", timeout=30000)
frame = wait_frame(page, sites.origin["B"], "/input", seconds=DEADLINE_S)
wait_for(page, lambda: frame.evaluate("() => document.readyState") == "complete")
box = page.evaluate("() => { const r = document.getElementById('f').getBoundingClientRect(); return [r.left, r.top]; }")
assert tuple(box) == FRAME_AT, "%s: the frame is at %r in the top document, the test placed it at %r" % (case, box, FRAME_AT)
for name, doc, origin in (("top", page, (0, 0)), ("frame", frame, FRAME_AT)):
_check_click(page, doc, origin, case, name)
_check_hover(page, doc, origin, case, name)
_check_drag(page, doc, origin, case, name)
_check_wheel(page, doc, origin, case, name)
"""Click, hover, drag and wheel reach the element under the cursor, in the top document and in a frame of another site, at every display scale.
The parent turns a point of the window into a point of the content with the matrix it keeps of each content process (``mChildToParentConversionMatrix``), and the
mouse, the wheel and the drag go through it. The matrix the parent SENDS to the child is a different one (it carries the window origin the page reads), and a change
there must not move the input: the point the parent hit-tests, the element the event is dispatched at and the ``clientX/Y`` it carries must stay the cursor's.
Playwright's own input (``page.mouse``) is what a client sends, so this is what a script sees break.
What it does, per display case (the four of the window tests), once for the top document and once for a frame of another site, 500x240 at (20, 200) of the same
page, both holding the same four boxes (CSS pixels of the document): a button ``click`` (60x40 at (20, 20)), a box ``hover`` (60x40 at (100, 20)), a box ``drag``
(140x90 at (180, 20)) and a scroller ``scroll`` (140x100 at (20, 80), 600 high inside). The mouse is the client's (``page.mouse``), the point is the box's own
centre plus the document's origin in the page:
* click: ``mouse.click`` at the centre of ``click``: the document hears trusted ``mousedown``, ``mouseup`` and ``click`` AT ``click``, with ``clientX/Y`` at the point
EXACTLY (no tolerance; every requested point is a whole CSS pixel);
* hover: ``mouse.move`` to the centre of ``hover``: ``mouseover`` is dispatched at ``hover``, at the exact point, and the element matches ``:hover``;
* drag: ``mousedown`` at the centre of ``drag``, six moves to a point 30 right and 20 below, ``mouseup``: ``mousedown`` and ``mouseup`` AT ``drag`` with the two points,
the ``mousemove`` events with the left button held and the last at the end point;
* wheel: ``mouse.wheel(0, 120)`` over the centre of ``scroll``: the document hears a trusted ``wheel`` at ``scroll``, at the exact point, and ``scroll.scrollTop`` grows.
The existing suites that read input in a frame of another site and are in the candidate's rows already: ``test_nested_frame_actions.py`` (a click, and a pointer at a large
offset, with the scales 1, 1.25, 1.5 and 2, in one-, two- and three-process pages, and the wheel at scales 1 and 1.25 under a zoom),
``test_a_click_in_an_iframe_lands_at_the_frames_own_screen_origin_e2e.py`` (one click), ``test_fission_frames_tree_input_and_pixels_e2e.py`` (clicks under a transform, after a
scroll, typing), ``test_a_drag_keeps_its_buttons_pressed_e2e.py`` and ``test_drag_motion.py`` (a drag in the top document), ``test_input_is_born_before_the_page_sees_it_e2e.py``
(keys and moves). None puts the four kinds of input in both documents at the four scales: this file does, and only this.
The engine that answers these values is not released yet: it must pass on the engine of the pin, where the matrix is the real one; it is red if the matrix the
parent sends moves the input.
"""
from __future__ import annotations
from typing import Any, Dict, List, Tuple
import pytest
from _fission_frames import Sites, wait_frame
from _window_origin import CASES, DEADLINE_S, launch_case, wait_for
pytestmark = pytest.mark.e2e
#: The boxes' centres in the document, CSS pixels.
CLICK, HOVER, DRAG, SCROLL = (50, 40), (130, 40), (250, 65), (90, 130)
DRAG_TO = (280, 85)
#: The frame's place in the top document.
FRAME_AT = (20, 200)
BODY = """<style>html,body{margin:0;padding:0}.b{position:absolute;box-sizing:border-box;margin:0;padding:0}
#click{left:20px;top:20px;width:60px;height:40px}#hover{left:100px;top:20px;width:60px;height:40px;background:#eee}
#drag{left:180px;top:20px;width:140px;height:90px;background:#9bd}
#scroll{left:20px;top:80px;width:140px;height:100px;overflow:auto;background:#bd9}#scroll div{height:600px}</style>
<button id=click class=b>click</button><div id=hover class=b>hover</div><div id=drag class=b>drag</div><div id=scroll class=b><div></div></div>
<script>
window.__ev = [];
const idOf = e => { const n = e.target.closest ? e.target.closest('[id]') : null; return n ? n.id : null; };
for (const t of ['click', 'mouseover', 'mousedown', 'mousemove', 'mouseup', 'wheel'])
document.addEventListener(t, e => { window.__ev.push({t: t, id: idOf(e), cx: e.clientX, cy: e.clientY, trusted: e.isTrusted, buttons: e.buttons}); }, true);
</script>"""
TOP = ("<!doctype html><meta charset=utf-8><title>input</title><style>#f{position:absolute;left:20px;top:200px;width:500px;height:240px;border:0}</style>"
+ BODY + '<iframe id=f src="%s"></iframe>')
FRAME = "<!doctype html><meta charset=utf-8><title>input frame</title>" + BODY
def _events(doc) -> List[Dict[str, Any]]:
return doc.evaluate("() => window.__ev")
def _where(case: str, doc_name: str, what: str, events: List[Dict[str, Any]]) -> str:
return "%s, %s document, %s: events heard %r" % (case, doc_name, what, events)
def _at(event: Dict[str, Any], point: Tuple[float, float], case: str) -> bool:
"""Exactly the requested point: no tolerance. Every requested point is a whole CSS pixel (the boxes' centres and the frame's origin are), so the event's
``clientX/Y`` of the document is that value at every scale."""
return (event["cx"], event["cy"]) == (point[0], point[1])
def _said(case: str, event: Dict[str, Any], point: Tuple[float, float]) -> str:
dpr = CASES[case][0]
return "requested point %r, received (%r, %r), scale %r" % (point, event["cx"], event["cy"], dpr)
def _of(events: List[Dict[str, Any]], kind: str, box: str) -> List[Dict[str, Any]]:
return [e for e in events if e["t"] == kind and e["id"] == box]
def _fresh(doc) -> None:
doc.evaluate("() => { window.__ev.length = 0; }")
def _check_click(page, doc, origin, case, name) -> None:
_fresh(doc)
page.mouse.click(origin[0] + CLICK[0], origin[1] + CLICK[1])
wait_for(page, lambda: _of(_events(doc), "click", "click"))
events = _events(doc)
where = _where(case, name, "click at %r" % (CLICK,), events)
for kind in ("mousedown", "mouseup", "click"):
heard = _of(events, kind, "click")
assert heard, "%s; no trusted %s at 'click'" % (where, kind)
assert heard[-1]["trusted"], "%s; %s is not trusted" % (where, kind)
assert _at(heard[-1], CLICK, case), "%s; %s is not at the point: %s" % (where, kind, _said(case, heard[-1], CLICK))
def _check_hover(page, doc, origin, case, name) -> None:
_fresh(doc)
page.mouse.move(origin[0] + HOVER[0], origin[1] + HOVER[1])
wait_for(page, lambda: _of(_events(doc), "mouseover", "hover"))
where = _where(case, name, "hover at %r" % (HOVER,), _events(doc))
over = _of(_events(doc), "mouseover", "hover")
assert over and over[-1]["trusted"], "%s; no trusted mouseover at 'hover'" % where
assert wait_for(page, lambda: doc.evaluate("() => document.getElementById('hover').matches(':hover')")), "%s; 'hover' does not match :hover" % where
moves = [e for e in _events(doc) if e["t"] == "mousemove"]
assert moves, "%s; no mousemove" % where
assert _at(moves[-1], HOVER, case), "%s; the last mousemove is not at the point: %s" % (where, _said(case, moves[-1], HOVER))
def _check_drag(page, doc, origin, case, name) -> None:
_fresh(doc)
page.mouse.move(origin[0] + DRAG[0], origin[1] + DRAG[1])
page.mouse.down()
page.mouse.move(origin[0] + DRAG_TO[0], origin[1] + DRAG_TO[1], steps=6)
page.mouse.up()
wait_for(page, lambda: _of(_events(doc), "mouseup", "drag"))
events = _events(doc)
where = _where(case, name, "drag from %r to %r" % (DRAG, DRAG_TO), events)
down, up = _of(events, "mousedown", "drag"), _of(events, "mouseup", "drag")
assert down and up, "%s; no mousedown or no mouseup at 'drag'" % where
assert _at(down[-1], DRAG, case), "%s; mousedown at 'drag' is not at the start point: %s" % (where, _said(case, down[-1], DRAG))
assert _at(up[-1], DRAG_TO, case), "%s; mouseup at 'drag' is not at the end point: %s" % (where, _said(case, up[-1], DRAG_TO))
held = [e for e in events if e["t"] == "mousemove" and e["buttons"] == 1]
assert held, "%s; no mousemove with the left button held" % where
assert _at(held[-1], DRAG_TO, case), "%s; the last mousemove with the left button held is not at the end point: %s" % (where, _said(case, held[-1], DRAG_TO))
def _check_wheel(page, doc, origin, case, name) -> None:
_fresh(doc)
page.mouse.move(origin[0] + SCROLL[0], origin[1] + SCROLL[1])
page.mouse.wheel(0, 120)
wait_for(page, lambda: doc.evaluate("() => document.getElementById('scroll').scrollTop") > 0 and _of(_events(doc), "wheel", "scroll"))
events = _events(doc)
where = _where(case, name, "wheel over %r" % (SCROLL,), events)
wheel = _of(events, "wheel", "scroll")
assert wheel and wheel[-1]["trusted"], "%s; no trusted wheel at 'scroll'" % where
assert _at(wheel[-1], SCROLL, case), "%s; the wheel is not at the point: %s" % (where, _said(case, wheel[-1], SCROLL))
assert doc.evaluate("() => document.getElementById('scroll').scrollTop") > 0, "%s; the scroller did not scroll" % where
@pytest.mark.parametrize("case", sorted(CASES))
def test_input_reaches_the_top_and_a_frame_of_another_site(firefox_binary, case):
with Sites() as sites:
sites.route("A", "/page", lambda handler: TOP % sites.url("B", "/input"))
sites.route("B", "/input", FRAME)
with launch_case(firefox_binary, case) as browser:
page = browser.new_page()
page.goto(sites.url("A", "/page"), wait_until="load", timeout=30000)
frame = wait_frame(page, sites.origin["B"], "/input", seconds=DEADLINE_S)
wait_for(page, lambda: frame.evaluate("() => document.readyState") == "complete")
box = page.evaluate("() => { const r = document.getElementById('f').getBoundingClientRect(); return [r.left, r.top]; }")
assert tuple(box) == FRAME_AT, "%s: the frame is at %r in the top document, the test placed it at %r" % (case, box, FRAME_AT)
for name, doc, origin in (("top", page, (0, 0)), ("frame", frame, FRAME_AT)):
_check_click(page, doc, origin, case, name)
_check_hover(page, doc, origin, case, name)
_check_drag(page, doc, origin, case, name)
_check_wheel(page, doc, origin, case, name)
@@ -1,188 +1,188 @@
"""What a frame of another site sees of the top viewport while the top scrolls: ``IntersectionObserver`` and lazy loading follow the page's own geometry.
A frame of another site runs in another process. It does not know where it is in the window: the parent tells it, as a matrix and as the part of the top viewport
that shows the frame (the remote document's visible rect). ``IntersectionObserver`` of a document in that frame, and the ``loading=lazy`` frames inside it,
read that rect. If the matrix the parent sends is moved from the real chrome offset to the declared one and the rect is not moved with it, the frame sees the
viewport shifted: its observer reports a ratio that is not the visible part of the frame, and a lazy frame loads too early or too late. Both are readable by any
page, and both have a right answer that does not depend on the window: what the top page itself reads of its own frame box.
HOW STOCK FIREFOX IS COMPARED. The wrapper's e2e jobs do not install Playwright's own Firefox: only the rows with ``stock_firefox`` in ``ci/required-suites.json``
(``wrapper.e2e.fakeweb`` and the host oracle) do, and they compare through ``scripts/``, not through a test of ``tests/``. So these tests do NOT run stock; they
compare with the value stock Firefox gives by its algorithm, computed from geometry the page reads (a ratio is the visible height over the frame height;
``rootBounds`` is null for a frame of another site, ``DOMIntersectionObserver.cpp``, ``isSimilarOrigin``; a nested lazy frame in a frame of another site loads when
its box meets the remote visible rect, which is not widened by the lazy margin, ``ComputeTheIntersection`` step 5, while a lazy frame of the top document
loads 600 CSS pixels before the viewport, ``dom.lazy-loading.margin.*``). A stock leg needs a row with ``stock_firefox`` and its legs in the gate.
1. The intersection of a frame, per display case (the four of the window tests). The top page is tall and holds a frame of another site, 300x300, at document y 1000.
The frame's page has a box ``#t`` of 300x300. Its script makes a NEW ``IntersectionObserver`` (threshold [0]) at every look, whose first callback always comes,
and reports ``isIntersecting``, ``intersectionRatio``, ``rootBounds``, ``boundingClientRect`` and ``intersectionRect``. The top scrolls (``scrollTo``) so that the frame's top
sits at a chosen place in the viewport: 100 (all visible), -50, -150, -250 (the top part clipped), -320 (all above, none visible), the viewport height less 60 (the bottom part
clipped), the viewport height plus 20 (all below), and 100 again. At each step the page's own ``getBoundingClientRect`` of the frame and ``clientHeight`` give the
expected visible height; the reading is waited for until it equals that, within one CSS pixel (scroll and box are snapped to device pixels), and the last one is
asserted: ``isIntersecting`` is whether any height is visible, the ratio is the visible height over 300, ``rootBounds`` is null, the box is 300x300, and the
intersection rect starts at the clipped height and is as high as the visible part. A frame that thinks the viewport starts a few pixels higher or lower reads another ratio.
2. Lazy frames, per display case. (a) A ``loading=lazy`` frame of another site in the top document, at document y 4000: it is not requested while its top is 640 CSS
pixels below the viewport, and is requested when it is 560 below. (b) A ``loading=lazy`` frame of a third site INSIDE a frame of another site, at y 200 of that frame,
which is itself at document y 4000: it is not requested while its top is 24 CSS pixels below the viewport's bottom edge, and is requested when it is 24 above it.
The "not requested" side is watched for 1.5 s, the requested side is waited for; the server's own record of requests says what was asked.
The engine that answers these values is not released yet: with a matrix moved and a rect not moved, the ratios and the lazy loads are off, so this test is RED there,
on purpose. It enters the suite with the engine release.
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Tuple
import pytest
from _fission_frames import Sites, wait_frame
from _window_origin import CASES, DEADLINE_S, launch_case, observe, wait_for
pytestmark = pytest.mark.e2e
FRAME_SIZE = 300
#: The frame's top in the top document, in CSS pixels.
IO_TOP = 1000
LAZY_TOP = 4000
#: One CSS pixel in the visible height: scroll and boxes are snapped to device pixels.
TOLERANCE_PX = 1.0
WATCH_S = 1.5
TOP_IO = """<!doctype html><meta charset=utf-8><title>io</title>
<style>html,body{margin:0;padding:0}body{height:4000px}
#f{position:absolute;left:20px;top:%dpx;width:300px;height:300px;border:0}</style>
<body><iframe id=f src="%%s"></iframe>""" % IO_TOP
FRAME_IO = """<!doctype html><meta charset=utf-8><title>io</title>
<style>html,body{margin:0;padding:0}#t{width:300px;height:300px;background:#9bd}</style><body><div id=t></div>"""
#: A new observer at every look: its first callback is always queued, whatever the thresholds, and carries the state now.
LOOK = """() => new Promise(resolve => {
const io = new IntersectionObserver(entries => {
const e = entries[entries.length - 1];
io.disconnect();
const box = r => r && {x: r.x, y: r.y, w: r.width, h: r.height};
resolve({isIntersecting: e.isIntersecting, ratio: e.intersectionRatio, rootBounds: box(e.rootBounds),
box: box(e.boundingClientRect), inter: box(e.intersectionRect)});
}, {threshold: [0]});
io.observe(document.getElementById('t'));
})"""
TOP_BOX = """() => { const r = document.getElementById('f').getBoundingClientRect(); return {top: r.top, vh: document.documentElement.clientHeight}; }"""
def _top_lazy(height: int, loading: str, src: str) -> str:
"""The top page of the lazy cases: a tall page with ONE frame of another site at document y ``LAZY_TOP``, ``height`` high; ``loading`` is the attribute's value."""
return ("<!doctype html><meta charset=utf-8><title>lazy</title>"
"<style>html,body{margin:0;padding:0}body{height:9000px}"
"iframe{position:absolute;left:20px;top:%dpx;width:300px;height:%dpx;border:0}</style>"
'<body><iframe id=f loading=%s src="%s"></iframe>' % (LAZY_TOP, height, loading, src))
FRAME_LAZY_HOST = """<!doctype html><meta charset=utf-8><title>host</title>
<style>html,body{margin:0;padding:0}iframe{position:absolute;left:0;top:200px;width:100px;height:50px;border:0}</style>
<body><iframe loading=lazy src="%s"></iframe>"""
LEAF = "<!doctype html><meta charset=utf-8><title>leaf</title><body>leaf"
def _expected(step_top: float, vh: float) -> Dict[str, float]:
"""What the observer of a 300x300 frame reports when the frame's top is ``step_top`` below the top of a viewport ``vh`` high, from geometry alone."""
shown_top = max(step_top, 0.0)
shown_bottom = min(step_top + FRAME_SIZE, vh)
visible = max(0.0, shown_bottom - shown_top)
return {"visible": visible, "ratio": visible / FRAME_SIZE, "inter_y": shown_top - step_top}
def _matches(reading: Dict[str, Any], expected: Dict[str, float]) -> bool:
ratio_tolerance = TOLERANCE_PX / FRAME_SIZE + 0.001
if abs(reading["ratio"] - expected["ratio"]) > ratio_tolerance:
return False
if reading["isIntersecting"] != (expected["visible"] > 0):
return False
return expected["visible"] == 0 or (reading["inter"] is not None and abs(reading["inter"]["h"] - expected["visible"]) <= TOLERANCE_PX
and abs(reading["inter"]["y"] - expected["inter_y"]) <= TOLERANCE_PX)
def _steps(vh: float) -> List[Tuple[str, float]]:
return [("all visible", 100), ("top 50 clipped", -50), ("top 150 clipped", -150), ("top 250 clipped", -250), ("all above", -320),
("bottom 240 clipped", vh - 60), ("all below", vh + 20), ("all visible again", 100)]
@pytest.mark.parametrize("case", sorted(CASES))
def test_the_intersection_of_a_frame_of_another_site_follows_the_scroll_of_the_top(firefox_binary, case):
with Sites() as sites:
sites.route("A", "/page", lambda handler: TOP_IO % sites.url("B", "/io"))
sites.route("B", "/io", FRAME_IO)
with launch_case(firefox_binary, case) as browser:
page = browser.new_page()
page.goto(sites.url("A", "/page"), wait_until="load", timeout=30000)
frame = wait_frame(page, sites.origin["B"], "/io", seconds=DEADLINE_S)
wait_for(page, lambda: frame.evaluate("() => document.readyState") == "complete")
vh = page.evaluate(TOP_BOX)["vh"]
for name, step_top in _steps(vh):
page.evaluate("(y) => window.scrollTo(0, y)", IO_TOP - step_top)
seen: Dict[str, Optional[Dict[str, Any]]] = {"reading": None, "box": None}
def right() -> bool:
box = page.evaluate(TOP_BOX)
seen["box"] = box
seen["reading"] = frame.evaluate(LOOK)
return _matches(seen["reading"], _expected(box["top"], box["vh"]))
wait_for(page, right)
reading, box = seen["reading"], seen["box"]
expected = _expected(box["top"], box["vh"])
where = "%s, step %r (the frame's top is %.2f in a viewport %r high): the frame read %r, from geometry the page expects %r" % (
case, name, box["top"], box["vh"], reading, expected)
assert _matches(reading, expected), where
assert reading["rootBounds"] is None, "%s; rootBounds of a frame of another site is null in stock Firefox" % where
assert (reading["box"]["w"], reading["box"]["h"]) == (FRAME_SIZE, FRAME_SIZE), "%s; the box of the target is 300x300 in the frame's own space" % where
def _scroll_so_that_the_frame_top_is(page, frame_top: float, to: float) -> None:
"""Scrolls the top so that an element at document y ``frame_top`` has its top ``to`` CSS pixels below the top of the viewport."""
page.evaluate("(y) => window.scrollTo(0, y)", frame_top - to)
@pytest.mark.parametrize("case", sorted(CASES))
def test_a_lazy_frame_loads_when_it_meets_the_viewport_it_is_told_about(firefox_binary, case):
with Sites() as sites:
sites.route("A", "/lazy-top", lambda handler: _top_lazy(100, "lazy", sites.url("B", "/leaf-top")))
sites.route("A", "/lazy-nested", lambda handler: _top_lazy(FRAME_SIZE, "eager", sites.url("B", "/host")))
sites.route("B", "/leaf-top", LEAF)
sites.route("B", "/host", lambda handler: FRAME_LAZY_HOST % sites.url("C", "/leaf-nested"))
sites.route("C", "/leaf-nested", LEAF)
with launch_case(firefox_binary, case) as browser:
page = browser.new_page()
# (a) a lazy frame of another site in the top document: 600 CSS pixels before the viewport (dom.lazy-loading.margin.*)
page.goto(sites.url("A", "/lazy-top"), wait_until="load", timeout=30000)
vh = page.evaluate(TOP_BOX)["vh"]
def requested_top() -> int:
return len(sites.seen("B", "/leaf-top"))
_scroll_so_that_the_frame_top_is(page, LAZY_TOP, vh + 640)
assert observe(page, requested_top, WATCH_S) == [0], (
"%s: a lazy frame of another site whose top is 640 CSS pixels below the viewport (the margin is 600) was requested" % case)
_scroll_so_that_the_frame_top_is(page, LAZY_TOP, vh + 560)
assert wait_for(page, lambda: requested_top() >= 1), (
"%s: a lazy frame of another site whose top is 560 CSS pixels below the viewport (the margin is 600) was not requested in %d s" % (case, DEADLINE_S))
# (b) a lazy frame inside a frame of another site: its box meets the remote visible rect, no margin
page.goto(sites.url("A", "/lazy-nested"), wait_until="load", timeout=30000)
wait_frame(page, sites.origin["B"], "/host", seconds=DEADLINE_S)
vh = page.evaluate(TOP_BOX)["vh"]
def requested_nested() -> int:
return len(sites.seen("C", "/leaf-nested"))
# the lazy frame is at y 200 of its host: its top is 24 below the bottom edge of the viewport when the host's top is vh - 176
_scroll_so_that_the_frame_top_is(page, LAZY_TOP, vh - 200 + 24)
assert observe(page, requested_nested, WATCH_S) == [0], (
"%s: a lazy frame inside a frame of another site whose top is 24 CSS pixels below the bottom edge of the top viewport was requested" % case)
_scroll_so_that_the_frame_top_is(page, LAZY_TOP, vh - 200 - 24)
assert wait_for(page, lambda: requested_nested() >= 1), (
"%s: a lazy frame inside a frame of another site whose top is 24 CSS pixels above the bottom edge of the top viewport was not requested in %d s"
% (case, DEADLINE_S))
"""What a frame of another site sees of the top viewport while the top scrolls: ``IntersectionObserver`` and lazy loading follow the page's own geometry.
A frame of another site runs in another process. It does not know where it is in the window: the parent tells it, as a matrix and as the part of the top viewport
that shows the frame (the remote document's visible rect). ``IntersectionObserver`` of a document in that frame, and the ``loading=lazy`` frames inside it,
read that rect. If the matrix the parent sends is moved from the real chrome offset to the declared one and the rect is not moved with it, the frame sees the
viewport shifted: its observer reports a ratio that is not the visible part of the frame, and a lazy frame loads too early or too late. Both are readable by any
page, and both have a right answer that does not depend on the window: what the top page itself reads of its own frame box.
HOW STOCK FIREFOX IS COMPARED. The wrapper's e2e jobs do not install Playwright's own Firefox: only the rows with ``stock_firefox`` in ``ci/required-suites.json``
(``wrapper.e2e.fakeweb`` and the host oracle) do, and they compare through ``scripts/``, not through a test of ``tests/``. So these tests do NOT run stock; they
compare with the value stock Firefox gives by its algorithm, computed from geometry the page reads (a ratio is the visible height over the frame height;
``rootBounds`` is null for a frame of another site, ``DOMIntersectionObserver.cpp``, ``isSimilarOrigin``; a nested lazy frame in a frame of another site loads when
its box meets the remote visible rect, which is not widened by the lazy margin, ``ComputeTheIntersection`` step 5, while a lazy frame of the top document
loads 600 CSS pixels before the viewport, ``dom.lazy-loading.margin.*``). A stock leg needs a row with ``stock_firefox`` and its legs in the gate.
1. The intersection of a frame, per display case (the four of the window tests). The top page is tall and holds a frame of another site, 300x300, at document y 1000.
The frame's page has a box ``#t`` of 300x300. Its script makes a NEW ``IntersectionObserver`` (threshold [0]) at every look, whose first callback always comes,
and reports ``isIntersecting``, ``intersectionRatio``, ``rootBounds``, ``boundingClientRect`` and ``intersectionRect``. The top scrolls (``scrollTo``) so that the frame's top
sits at a chosen place in the viewport: 100 (all visible), -50, -150, -250 (the top part clipped), -320 (all above, none visible), the viewport height less 60 (the bottom part
clipped), the viewport height plus 20 (all below), and 100 again. At each step the page's own ``getBoundingClientRect`` of the frame and ``clientHeight`` give the
expected visible height; the reading is waited for until it equals that, within one CSS pixel (scroll and box are snapped to device pixels), and the last one is
asserted: ``isIntersecting`` is whether any height is visible, the ratio is the visible height over 300, ``rootBounds`` is null, the box is 300x300, and the
intersection rect starts at the clipped height and is as high as the visible part. A frame that thinks the viewport starts a few pixels higher or lower reads another ratio.
2. Lazy frames, per display case. (a) A ``loading=lazy`` frame of another site in the top document, at document y 4000: it is not requested while its top is 640 CSS
pixels below the viewport, and is requested when it is 560 below. (b) A ``loading=lazy`` frame of a third site INSIDE a frame of another site, at y 200 of that frame,
which is itself at document y 4000: it is not requested while its top is 24 CSS pixels below the viewport's bottom edge, and is requested when it is 24 above it.
The "not requested" side is watched for 1.5 s, the requested side is waited for; the server's own record of requests says what was asked.
The engine that answers these values is not released yet: with a matrix moved and a rect not moved, the ratios and the lazy loads are off, so this test is RED there,
on purpose. It enters the suite with the engine release.
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Tuple
import pytest
from _fission_frames import Sites, wait_frame
from _window_origin import CASES, DEADLINE_S, launch_case, observe, wait_for
pytestmark = pytest.mark.e2e
FRAME_SIZE = 300
#: The frame's top in the top document, in CSS pixels.
IO_TOP = 1000
LAZY_TOP = 4000
#: One CSS pixel in the visible height: scroll and boxes are snapped to device pixels.
TOLERANCE_PX = 1.0
WATCH_S = 1.5
TOP_IO = """<!doctype html><meta charset=utf-8><title>io</title>
<style>html,body{margin:0;padding:0}body{height:4000px}
#f{position:absolute;left:20px;top:%dpx;width:300px;height:300px;border:0}</style>
<body><iframe id=f src="%%s"></iframe>""" % IO_TOP
FRAME_IO = """<!doctype html><meta charset=utf-8><title>io</title>
<style>html,body{margin:0;padding:0}#t{width:300px;height:300px;background:#9bd}</style><body><div id=t></div>"""
#: A new observer at every look: its first callback is always queued, whatever the thresholds, and carries the state now.
LOOK = """() => new Promise(resolve => {
const io = new IntersectionObserver(entries => {
const e = entries[entries.length - 1];
io.disconnect();
const box = r => r && {x: r.x, y: r.y, w: r.width, h: r.height};
resolve({isIntersecting: e.isIntersecting, ratio: e.intersectionRatio, rootBounds: box(e.rootBounds),
box: box(e.boundingClientRect), inter: box(e.intersectionRect)});
}, {threshold: [0]});
io.observe(document.getElementById('t'));
})"""
TOP_BOX = """() => { const r = document.getElementById('f').getBoundingClientRect(); return {top: r.top, vh: document.documentElement.clientHeight}; }"""
def _top_lazy(height: int, loading: str, src: str) -> str:
"""The top page of the lazy cases: a tall page with ONE frame of another site at document y ``LAZY_TOP``, ``height`` high; ``loading`` is the attribute's value."""
return ("<!doctype html><meta charset=utf-8><title>lazy</title>"
"<style>html,body{margin:0;padding:0}body{height:9000px}"
"iframe{position:absolute;left:20px;top:%dpx;width:300px;height:%dpx;border:0}</style>"
'<body><iframe id=f loading=%s src="%s"></iframe>' % (LAZY_TOP, height, loading, src))
FRAME_LAZY_HOST = """<!doctype html><meta charset=utf-8><title>host</title>
<style>html,body{margin:0;padding:0}iframe{position:absolute;left:0;top:200px;width:100px;height:50px;border:0}</style>
<body><iframe loading=lazy src="%s"></iframe>"""
LEAF = "<!doctype html><meta charset=utf-8><title>leaf</title><body>leaf"
def _expected(step_top: float, vh: float) -> Dict[str, float]:
"""What the observer of a 300x300 frame reports when the frame's top is ``step_top`` below the top of a viewport ``vh`` high, from geometry alone."""
shown_top = max(step_top, 0.0)
shown_bottom = min(step_top + FRAME_SIZE, vh)
visible = max(0.0, shown_bottom - shown_top)
return {"visible": visible, "ratio": visible / FRAME_SIZE, "inter_y": shown_top - step_top}
def _matches(reading: Dict[str, Any], expected: Dict[str, float]) -> bool:
ratio_tolerance = TOLERANCE_PX / FRAME_SIZE + 0.001
if abs(reading["ratio"] - expected["ratio"]) > ratio_tolerance:
return False
if reading["isIntersecting"] != (expected["visible"] > 0):
return False
return expected["visible"] == 0 or (reading["inter"] is not None and abs(reading["inter"]["h"] - expected["visible"]) <= TOLERANCE_PX
and abs(reading["inter"]["y"] - expected["inter_y"]) <= TOLERANCE_PX)
def _steps(vh: float) -> List[Tuple[str, float]]:
return [("all visible", 100), ("top 50 clipped", -50), ("top 150 clipped", -150), ("top 250 clipped", -250), ("all above", -320),
("bottom 240 clipped", vh - 60), ("all below", vh + 20), ("all visible again", 100)]
@pytest.mark.parametrize("case", sorted(CASES))
def test_the_intersection_of_a_frame_of_another_site_follows_the_scroll_of_the_top(firefox_binary, case):
with Sites() as sites:
sites.route("A", "/page", lambda handler: TOP_IO % sites.url("B", "/io"))
sites.route("B", "/io", FRAME_IO)
with launch_case(firefox_binary, case) as browser:
page = browser.new_page()
page.goto(sites.url("A", "/page"), wait_until="load", timeout=30000)
frame = wait_frame(page, sites.origin["B"], "/io", seconds=DEADLINE_S)
wait_for(page, lambda: frame.evaluate("() => document.readyState") == "complete")
vh = page.evaluate(TOP_BOX)["vh"]
for name, step_top in _steps(vh):
page.evaluate("(y) => window.scrollTo(0, y)", IO_TOP - step_top)
seen: Dict[str, Optional[Dict[str, Any]]] = {"reading": None, "box": None}
def right() -> bool:
box = page.evaluate(TOP_BOX)
seen["box"] = box
seen["reading"] = frame.evaluate(LOOK)
return _matches(seen["reading"], _expected(box["top"], box["vh"]))
wait_for(page, right)
reading, box = seen["reading"], seen["box"]
expected = _expected(box["top"], box["vh"])
where = "%s, step %r (the frame's top is %.2f in a viewport %r high): the frame read %r, from geometry the page expects %r" % (
case, name, box["top"], box["vh"], reading, expected)
assert _matches(reading, expected), where
assert reading["rootBounds"] is None, "%s; rootBounds of a frame of another site is null in stock Firefox" % where
assert (reading["box"]["w"], reading["box"]["h"]) == (FRAME_SIZE, FRAME_SIZE), "%s; the box of the target is 300x300 in the frame's own space" % where
def _scroll_so_that_the_frame_top_is(page, frame_top: float, to: float) -> None:
"""Scrolls the top so that an element at document y ``frame_top`` has its top ``to`` CSS pixels below the top of the viewport."""
page.evaluate("(y) => window.scrollTo(0, y)", frame_top - to)
@pytest.mark.parametrize("case", sorted(CASES))
def test_a_lazy_frame_loads_when_it_meets_the_viewport_it_is_told_about(firefox_binary, case):
with Sites() as sites:
sites.route("A", "/lazy-top", lambda handler: _top_lazy(100, "lazy", sites.url("B", "/leaf-top")))
sites.route("A", "/lazy-nested", lambda handler: _top_lazy(FRAME_SIZE, "eager", sites.url("B", "/host")))
sites.route("B", "/leaf-top", LEAF)
sites.route("B", "/host", lambda handler: FRAME_LAZY_HOST % sites.url("C", "/leaf-nested"))
sites.route("C", "/leaf-nested", LEAF)
with launch_case(firefox_binary, case) as browser:
page = browser.new_page()
# (a) a lazy frame of another site in the top document: 600 CSS pixels before the viewport (dom.lazy-loading.margin.*)
page.goto(sites.url("A", "/lazy-top"), wait_until="load", timeout=30000)
vh = page.evaluate(TOP_BOX)["vh"]
def requested_top() -> int:
return len(sites.seen("B", "/leaf-top"))
_scroll_so_that_the_frame_top_is(page, LAZY_TOP, vh + 640)
assert observe(page, requested_top, WATCH_S) == [0], (
"%s: a lazy frame of another site whose top is 640 CSS pixels below the viewport (the margin is 600) was requested" % case)
_scroll_so_that_the_frame_top_is(page, LAZY_TOP, vh + 560)
assert wait_for(page, lambda: requested_top() >= 1), (
"%s: a lazy frame of another site whose top is 560 CSS pixels below the viewport (the margin is 600) was not requested in %d s" % (case, DEADLINE_S))
# (b) a lazy frame inside a frame of another site: its box meets the remote visible rect, no margin
page.goto(sites.url("A", "/lazy-nested"), wait_until="load", timeout=30000)
wait_frame(page, sites.origin["B"], "/host", seconds=DEADLINE_S)
vh = page.evaluate(TOP_BOX)["vh"]
def requested_nested() -> int:
return len(sites.seen("C", "/leaf-nested"))
# the lazy frame is at y 200 of its host: its top is 24 below the bottom edge of the viewport when the host's top is vh - 176
_scroll_so_that_the_frame_top_is(page, LAZY_TOP, vh - 200 + 24)
assert observe(page, requested_nested, WATCH_S) == [0], (
"%s: a lazy frame inside a frame of another site whose top is 24 CSS pixels below the bottom edge of the top viewport was requested" % case)
_scroll_so_that_the_frame_top_is(page, LAZY_TOP, vh - 200 - 24)
assert wait_for(page, lambda: requested_nested() >= 1), (
"%s: a lazy frame inside a frame of another site whose top is 24 CSS pixels above the bottom edge of the top viewport was not requested in %d s"
% (case, DEADLINE_S))