tests: the focus and fullscreen window tests judge after the event, not after a pause

The focus test is wall_clock (it runs alone, after the parallel tests), its two
sessions share a private Xvfb on Linux, and before judging it reads from the OS
that the focus is where the step says (X input focus, GetForegroundWindow on
Windows); "no blur" is judged after that and a round trip to the page's process
instead of a two-frame pause.

The fullscreen test waits for the condition itself with the engine on (declared
size, display-mode fullscreen, fullscreenElement) and for fullscreenchange and
the following resize with it off; on Windows it reads the monitor first and
declares a size that is not the monitor's.
This commit is contained in:
feder-cr committed 2026-11-22 10:17:09 +01:00
1 parent ac5a519244
commit 3f4ee5c61e
3 files changed
+257 -32

No files matched your search

+126
View File
@@ -0,0 +1,126 @@
"""What the window e2e tests ask the operating system itself: which window holds the input focus, on a display of the test's own.
A page's ``document.hasFocus()`` is what the engine reports. A test that judges "the first session kept the focus when another one took the display" must
first know that the OS did give the focus to the second session's window; otherwise a green means only that nothing happened (the second window never took
it, or took it later than the read). The OS answers that without the engine:
* Linux: the X input focus (``XGetInputFocus`` on the display the sessions share); the display is a private Xvfb started for the test (``a_display_of_its_own``),
so no other test's headed window moves the focus in it;
* Windows: the foreground window (``GetForegroundWindow``), the window of the session found by the title its page gave it.
"""
from __future__ import annotations
import contextlib
import ctypes
import subprocess
import sys
import threading
from typing import Iterator, Optional
#: ``None`` and ``PointerRoot``: what the X input focus is when no client holds it.
_X_NO_WINDOW = (0, 1)
@contextlib.contextmanager
def a_display_of_its_own(monkeypatch) -> Iterator[str]:
"""Linux: a private Xvfb (the number chosen by the server, ``-displayfd``), set as ``DISPLAY`` for the test and stopped at its end.
Two headed sessions started inside it see each other and nothing else; the Xvfb of ``xvfb-run`` that the parallel workers share is never touched."""
process = subprocess.Popen(["Xvfb", "-displayfd", "1", "-screen", "0", "1920x1080x24", "-nolisten", "tcp"],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
answer = {}
reader = threading.Thread(target=lambda: answer.setdefault("line", process.stdout.readline()), daemon=True)
reader.start()
try:
reader.join(60)
number = answer.get("line", "").strip()
assert number.isdigit(), "the private Xvfb did not give a display number (it said %r, exit %r)" % (number, process.poll())
monkeypatch.setenv("DISPLAY", ":" + number)
for name in ("WAYLAND_DISPLAY", "XAUTHORITY"):
monkeypatch.delenv(name, raising=False)
yield ":" + number
finally:
process.terminate()
try:
process.wait(30)
except subprocess.TimeoutExpired:
process.kill()
process.wait(30)
process.stdout.close()
class XFocus:
"""The X input focus of a display, read through a connection of its own (libX11, as the engine's own client library)."""
def __init__(self, display: str) -> None:
self.x11 = ctypes.CDLL("libX11.so.6")
self.x11.XOpenDisplay.restype, self.x11.XOpenDisplay.argtypes = ctypes.c_void_p, (ctypes.c_char_p,)
self.x11.XGetInputFocus.argtypes = (ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_int))
self.x11.XCloseDisplay.argtypes = (ctypes.c_void_p,)
self.connection = self.x11.XOpenDisplay(display.encode())
assert self.connection, "no connection to the display %r" % display
def holder(self) -> int:
window, revert = ctypes.c_ulong(), ctypes.c_int()
self.x11.XGetInputFocus(self.connection, ctypes.byref(window), ctypes.byref(revert))
return int(window.value)
def is_a_window(self, holder: int) -> bool:
return holder not in _X_NO_WINDOW
def close(self) -> None:
self.x11.XCloseDisplay(self.connection)
self.connection = None
class ForegroundWindow:
"""Windows: the foreground window of the desktop the sessions run on, and the Firefox window a title names."""
def __init__(self) -> None:
from ctypes import wintypes
self.user32 = ctypes.WinDLL("user32", use_last_error=True)
self.user32.GetForegroundWindow.restype = wintypes.HWND
self.user32.SetForegroundWindow.argtypes = (wintypes.HWND,)
self.enum = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
def holder(self) -> int:
return self.user32.GetForegroundWindow() or 0
def is_a_window(self, holder: int) -> bool:
return bool(holder)
def window_titled(self, title: str) -> Optional[int]:
"""The one visible top-level Firefox window whose title starts with ``title``, or None (none, or more than one)."""
found = []
def each(hwnd, _):
name, text = ctypes.create_unicode_buffer(256), ctypes.create_unicode_buffer(512)
self.user32.GetClassNameW(hwnd, name, 256)
self.user32.GetWindowTextW(hwnd, text, 512)
if name.value.startswith("MozillaWindowClass") and text.value.startswith(title) and self.user32.IsWindowVisible(hwnd):
found.append(hwnd)
return True
self.user32.EnumWindows(self.enum(each), 0)
return found[0] if len(found) == 1 else None
def ask_for_the_foreground(self, hwnd: int) -> int:
"""What a user does by clicking the window: the system may refuse it, and then the foreground is what the test reads."""
self.user32.SetForegroundWindow(hwnd)
return self.holder()
def host_monitor_size() -> Optional[tuple]:
"""Windows: the primary monitor in device pixels (the reading of a per-monitor-aware process, whatever the test's own awareness is); None elsewhere."""
if sys.platform != "win32":
return None
user32 = ctypes.WinDLL("user32")
user32.SetThreadDpiAwarenessContext.restype = ctypes.c_void_p
user32.SetThreadDpiAwarenessContext.argtypes = (ctypes.c_void_p,)
previous = user32.SetThreadDpiAwarenessContext(ctypes.c_void_p(-4))
try:
return (user32.GetSystemMetrics(0), user32.GetSystemMetrics(1))
finally:
if previous:
user32.SetThreadDpiAwarenessContext(ctypes.c_void_p(previous))
@@ -14,12 +14,24 @@ still reads ``hasFocus()`` true and has recorded no ``blur``. Then A opens a sec
The control, in the same test: ``extra_prefs={"zoom.stealth.focus.ignore_os_deactivation": False}``, the same steps up to B taking the display, and A's page
reads ``hasFocus()`` false. It runs first, so a runner where the second session does not take the focus is red there and not a green that means nothing.
Both sessions are headed on one display (the Linux e2e runs under ``xvfb-run``; Windows has the interactive desktop of the runner).
Both sessions are headed on one display, and the test owns it: on Linux a private Xvfb started for the test (the ``xvfb-run`` display that the four workers
share is never used, so no neighbour's headed window moves the focus); on Windows the interactive desktop of the runner, which only this test touches because
it is ``wall_clock`` (the e2e run gives such a test the machine alone, after the parallel tests).
What the verdict waits for is the operating system, not a pause: before anything is judged the test reads from the OS that the focus really is where the step
says (the X input focus on Linux, ``GetForegroundWindow`` on Windows: first the first session's window, then the second session's window). "No blur" is judged
after that and after a round trip to the first page's own process (two painted frames), which handles everything the parent sent it before: the deactivation
that would cause a blur has been delivered by then, so a late one cannot give a false green.
"""
from __future__ import annotations
import contextlib
import sys
import pytest
from _os_focus import ForegroundWindow, XFocus, a_display_of_its_own
from _window_sessions import in_a_thread_of_its_own, launch, wait_for_condition
pytestmark = pytest.mark.e2e
@@ -33,28 +45,76 @@ RECORD = """() => {
}"""
HAS_FOCUS = "() => document.hasFocus()"
EVENTS = "() => window.__events"
TWO_FRAMES = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))"
#: A round trip to the page's own process: it has handled what the parent sent it before this ran (the deactivation, if the parent had one to send).
ROUND_TRIP = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))"
#: Names the page, so that on Windows its top-level window is found by its title.
NAME = "(name) => { document.title = name; return document.title; }"
FIRST_TITLE, SECOND_TITLE = "focus-first-session", "focus-second-session"
@contextlib.contextmanager
def the_os_focus(monkeypatch):
"""What tells where the OS has put the focus, on a display this test owns (see the module docstring)."""
if sys.platform == "win32":
yield ForegroundWindow()
return
with a_display_of_its_own(monkeypatch) as display:
reader = XFocus(display)
try:
yield reader
finally:
reader.close()
def takes_the_focus(b):
"""Runs in the second session's own thread: opens a window and waits until its page has the focus."""
"""Runs in the second session's own thread: opens a window, names it, and waits until its page has the focus."""
taker = b.new_page()
taker.goto("about:blank")
taker.evaluate(NAME, SECOND_TITLE)
wait_for_condition(taker, lambda: taker.evaluate(HAS_FOCUS), lambda focused: focused is True, "the second session's page never took the focus")
def another_session_takes_the_display(firefox_binary, keeps, with_own_page=False):
def os_focus_is_on_the_first_window(first, os_focus):
"""Waits until the OS says the first session's window holds the focus; gives what holds it."""
if sys.platform == "win32":
window = wait_for_condition(first, lambda: os_focus.window_titled(FIRST_TITLE), lambda hwnd: hwnd is not None,
"no single visible top-level window is titled %r" % FIRST_TITLE).history[-1][1]
wait_for_condition(first, lambda: os_focus.ask_for_the_foreground(window), lambda holder: holder == window,
"the first session's window never became the foreground window")
return window
seen = wait_for_condition(first, os_focus.holder, os_focus.is_a_window, "no window of the display ever held the X input focus")
return seen.history[-1][1]
def os_focus_is_on_the_second_window(first, os_focus, before):
"""Waits until the OS says a window other than the first one holds the focus (on Windows: the second session's window, by its title)."""
if sys.platform == "win32":
window = wait_for_condition(first, lambda: os_focus.window_titled(SECOND_TITLE), lambda hwnd: hwnd is not None,
"no single visible top-level window is titled %r" % SECOND_TITLE).history[-1][1]
assert window != before, "the second session's window is the first one's"
wait_for_condition(first, lambda: os_focus.ask_for_the_foreground(window), lambda holder: holder == window,
"the second session's window never became the foreground window")
return
wait_for_condition(first, os_focus.holder, lambda holder: os_focus.is_a_window(holder) and holder != before,
"the X input focus never left the first session's window %r" % before)
def another_session_takes_the_display(firefox_binary, os_focus, keeps, with_own_page=False):
"""What A's page reads once B's window has the focus, and (``with_own_page``) once A has opened a page of its own."""
extra = None if keeps else {PREF: False}
with launch(firefox_binary, extra_prefs=extra) as a:
first = a.new_page()
first.goto("about:blank")
first.evaluate(NAME, FIRST_TITLE)
first.evaluate(RECORD)
wait_for_condition(first, lambda: first.evaluate(HAS_FOCUS), lambda focused: focused is True, "the page never had the focus of its own window")
before = os_focus_is_on_the_first_window(first, os_focus)
with in_a_thread_of_its_own(firefox_binary) as b:
b.run(takes_the_focus)
os_focus_is_on_the_second_window(first, os_focus, before)
if keeps:
first.evaluate(TWO_FRAMES)
# the OS has moved the focus; one round trip to the page's process orders the read after the deactivation that would have followed
first.evaluate(ROUND_TRIP)
else:
wait_for_condition(first, lambda: first.evaluate(HAS_FOCUS), lambda focused: focused is False,
"the first page still has the focus although another session's window took it")
@@ -69,11 +129,13 @@ def another_session_takes_the_display(firefox_binary, keeps, with_own_page=False
return seen
def test_a_page_keeps_focus_when_another_session_takes_the_display(firefox_binary):
control = another_session_takes_the_display(firefox_binary, keeps=False)
assert control["has_focus"] is False, "control: without the pref the first page still has the focus: %r" % control
@pytest.mark.wall_clock
def test_a_page_keeps_focus_when_another_session_takes_the_display(firefox_binary, monkeypatch):
with the_os_focus(monkeypatch) as os_focus:
control = another_session_takes_the_display(firefox_binary, os_focus, keeps=False)
assert control["has_focus"] is False, "control: without the pref the first page still has the focus: %r" % control
kept = another_session_takes_the_display(firefox_binary, keeps=True, with_own_page=True)
kept = another_session_takes_the_display(firefox_binary, os_focus, keeps=True, with_own_page=True)
assert kept["has_focus"] is True, "with the pref the first page lost the focus to another session: %r" % kept
assert "blur" not in kept["events"], "with the pref the first page recorded a blur when another session took the display: %r" % kept
assert kept["has_focus"] != control["has_focus"]
+60 -23
View File
@@ -9,14 +9,19 @@ The hook: ``nsWindow::MakeFullScreen`` in ``widget/gtk/nsWindow.cpp`` of the ser
``fingerprint/screen-window/geometry``, whose function ``StealthMakeFullScreenWithoutWM`` in ``widget/gtk/StealthFullscreenGtk.cpp`` it calls). On Windows
the same reading is held by ``nsIWidget::InfallibleMakeFullScreen`` and the Win32 rules of the same folder (``geometry``).
The screen is pinned to 1600x900, which no runner has (the Linux display is 1920x1080, the Windows runner's monitor 1024x768 or 1920x1080), so a window that
filled the host would read differently from the declared one.
The screen is pinned to 1600x900, which no Linux runner has (the display is 1920x1080); on Windows the test reads the runner's monitor first (the primary one, in
device pixels, and in CSS pixels at the usual scale factors) and declares the first of 1600x900, 1366x768 and 1280x720 that is none of them, so a window that
filled the host always reads differently from the declared one, whatever monitor the runner has.
The control, in the same test: the engine inactive (``zoom.stealth.fpp.hw_seed`` 0: the engine is on when it is above 0) keeps Mozilla's behaviour. On
Linux without a window manager that is the refusal (``display-mode: fullscreen`` false and the window not the declared screen); on Windows, which always has a
window manager and a widget that decides fullscreen, it is the host's monitor, not the declared screen. The same click, the same pinned screen; only the engine
differs.
What the verdict waits for is the condition itself, not a count of equal looks: with the engine on, until the page reads the declared size AND ``display-mode:
fullscreen`` AND a ``fullscreenElement`` (a red names the last geometry seen); with the engine off, until ``fullscreenchange`` (or ``fullscreenerror``) was heard
and, where the window really changes size (Windows), the ``resize`` the change causes was heard too, then one round trip to the page's own process.
The click is real input (``page.mouse``): ``requestFullscreen`` needs a user gesture. A page reads it from ``innerWidth``, ``innerHeight``,
``matchMedia('(display-mode: fullscreen)')`` and ``document.fullscreenElement``.
"""
@@ -28,20 +33,37 @@ import threading
import pytest
from _os_focus import host_monitor_size
from _servers import LocalServer
from _window_sessions import launch, wait_for_condition
from _waits import watch
from _window_sessions import DEADLINE_S, launch
pytestmark = pytest.mark.e2e
#: The device pixel ratio is pinned too: the core declares 1.5 for some personas (Windows runner), and a page reads the screen and the window in
#: CSS pixels, declared / dpr (1067x600), which is not what this test is about.
DECLARED = {"screen.width": 1600, "screen.height": 900, "screen.dpr": 1.0}
CANDIDATES = ((1600, 900), (1366, 768), (1280, 720))
#: The scale factors at which a monitor of the host reads, in CSS pixels, smaller than it is.
SCALES = (1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0)
def declared_screen():
"""The declared screen: 1600x900 unless the host's monitor (Windows) is that size, at any usual scale; then the first candidate that it is not."""
monitor = host_monitor_size()
if monitor is None:
return CANDIDATES[0]
taken = {(round(monitor[0] / scale), round(monitor[1] / scale)) for scale in SCALES}
for width, height in CANDIDATES:
if not any(abs(width - w) <= 1 and abs(height - h) <= 1 for w, h in taken):
return width, height
raise AssertionError("every candidate declared screen %r is a size of the host's monitor %r" % (CANDIDATES, monitor))
PAGE = (b"<!doctype html><html><head><meta charset=utf-8><title>fullscreen</title></head><body style=\"margin:0\">"
b"<button id=go style=\"position:fixed;left:20px;top:20px;width:160px;height:40px;margin:0\">fullscreen</button>"
b"<script>"
b"window.__how = null; window.__error = null;"
b"for (const t of ['fullscreenchange', 'fullscreenerror']) document.addEventListener(t, () => { window.__how = window.__how || t; });"
b"window.__how = null; window.__error = null; window.__order = [];"
b"for (const t of ['fullscreenchange', 'fullscreenerror']) document.addEventListener(t, () => { window.__how = window.__how || t; window.__order.push(t); });"
b"window.addEventListener('resize', () => window.__order.push('resize'));"
b"document.getElementById('go').addEventListener('click', () => {"
b" document.documentElement.requestFullscreen().catch(e => { window.__error = String(e); });"
b"});"
@@ -54,6 +76,9 @@ GEOMETRY = """() => ({
fullscreenElement: document.fullscreenElement !== null,
})"""
HOW = "() => [window.__how, window.__error]"
ORDER = "() => window.__order"
#: A round trip to the page's own process: it has handled what the parent sent it before this ran.
ROUND_TRIP = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))"
@pytest.fixture
@@ -77,35 +102,47 @@ def page_url():
server.shutdown()
def fullscreen_geometry(firefox_binary, page_url, engine_on):
"""The page's geometry once the window has held still after a click on a button that asks for fullscreen."""
def fullscreen_geometry(firefox_binary, page_url, engine_on, declared):
"""The page's geometry once the fullscreen request has been answered: the condition with the engine on, the events with it off (see the module docstring)."""
extra = None if engine_on else {"zoom.stealth.fpp.hw_seed": 0}
with launch(firefox_binary, extra_prefs=extra, pin=DECLARED, headless=True) as browser:
pin = {"screen.width": declared[0], "screen.height": declared[1], "screen.dpr": 1.0}
with launch(firefox_binary, extra_prefs=extra, pin=pin, headless=True) as browser:
page = browser.new_page()
page.goto(page_url)
page.mouse.move(90, 40)
page.mouse.click(100, 40)
wait_for_condition(page, lambda: page.evaluate(HOW), lambda how: how[0] is not None,
"the click on a button that asks for fullscreen was followed by neither fullscreenchange nor fullscreenerror")
seen = []
def held_still(geometry):
seen.append(geometry)
return len(seen) >= 4 and all(g == geometry for g in seen[-4:])
def pump():
page.wait_for_timeout(100)
# a transition resizes in steps: the geometry counts once it has been the same for four looks in a row
wait_for_condition(page, lambda: page.evaluate(GEOMETRY), held_still, "the window never held still after the fullscreen request")
return dict(seen[-1], how=page.evaluate(HOW))
answered = watch(lambda: page.evaluate(HOW), lambda how: how[0] is not None, DEADLINE_S, pump)
assert answered.ok, ("the click on a button that asks for fullscreen was followed by neither fullscreenchange nor fullscreenerror; seen: %s"
% answered.render())
if engine_on:
def is_the_declared_fullscreen(geometry):
return ((geometry["innerWidth"], geometry["innerHeight"]) == declared
and geometry["displayModeFullscreen"] is True and geometry["fullscreenElement"] is True)
# the assertions of the test judge the last geometry seen: a window that never gets there is red there, with what it read
watch(lambda: page.evaluate(GEOMETRY), is_the_declared_fullscreen, DEADLINE_S, pump)
else:
if sys.platform == "win32":
# the window really changes size: the change is over once the resize that goes with fullscreenchange was heard (a window that was
# already the size of the screen has none to hear: the geometry read below is then what judges)
watch(lambda: page.evaluate(ORDER), lambda order: "fullscreenchange" in order and "resize" in order, DEADLINE_S, pump)
page.evaluate(ROUND_TRIP)
return dict(page.evaluate(GEOMETRY), how=page.evaluate(HOW))
def test_fullscreen_without_a_window_manager_is_the_declared_screen(firefox_binary, page_url):
on = fullscreen_geometry(firefox_binary, page_url, engine_on=True)
assert on["screen"] == [1600, 900], "the pinned screen is not what the page reads: %r" % on
assert (on["innerWidth"], on["innerHeight"]) == (1600, 900), "with the engine on the fullscreen window is not the declared screen: %r" % on
declared = declared_screen()
on = fullscreen_geometry(firefox_binary, page_url, engine_on=True, declared=declared)
assert on["screen"] == list(declared), "the pinned screen is not what the page reads: %r" % on
assert (on["innerWidth"], on["innerHeight"]) == declared, "with the engine on the fullscreen window is not the declared screen: %r" % on
assert on["displayModeFullscreen"] is True and on["fullscreenElement"] is True, "with the engine on the page does not read fullscreen: %r" % on
off = fullscreen_geometry(firefox_binary, page_url, engine_on=False)
assert (off["innerWidth"], off["innerHeight"]) != (1600, 900), "control: the engine inactive also gives the declared screen: %r" % off
off = fullscreen_geometry(firefox_binary, page_url, engine_on=False, declared=declared)
assert (off["innerWidth"], off["innerHeight"]) != declared, "control: the engine inactive also gives the declared screen: %r" % off
if sys.platform != "win32":
# no window manager: Mozilla's refusal, the DOM fullscreen without the window
assert off["displayModeFullscreen"] is False, "control: without a window manager and without the engine the window went fullscreen: %r" % off