Compare commits

...
4 changed files with 368 additions and 0 deletions

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
"""What the window e2e tests share: a headed session of the product, and a wait on a condition of a page.
The sessions are HEADED on purpose. ``headless=True`` gives every session a display of its own (a fresh Xvfb on Linux, a fresh Win32 desktop on
Windows), so two of them never see each other; the focus and occlusion tests need two windows on ONE display, which is what two headed sessions of the
same run have (the Linux e2e runs under ``xvfb-run``). Both sessions use the same seed, so both windows are the same declared window and the second one
covers the first completely.
The first session is the one of the test's own thread; the second one lives in a thread of its own (``in_a_thread_of_its_own``, the pattern of
``test_popups_reach_the_client_e2e.py``): an open sync client keeps its asyncio loop marked as running in the thread that started it, and a second sync client
refuses to start there ("It looks like you are using Playwright Sync API inside the asyncio loop"). A sync client's objects belong to the thread that made
them, so everything the test does with the second session is handed to that thread (``run``).
"""
from __future__ import annotations
import contextlib
import queue
import threading
from typing import Any, Callable, Dict, Iterator, Optional
from _waits import Watch, watch
#: The seed only has to give two sessions the same window.
SEED = 21
#: The deadline of a wait for something that must happen, in seconds.
DEADLINE_S = 30
def launch(firefox_binary: str, *, extra_prefs: Optional[Dict[str, Any]] = None, pin: Optional[Dict[str, Any]] = None, headless: bool = False):
"""A session of the product (RFP off, the engine declared as the core launches it); ``extra_prefs`` and ``pin`` only where a test needs them."""
from invisible_playwright import InvisiblePlaywright
return InvisiblePlaywright(seed=SEED, binary_path=firefox_binary, headless=headless, locale="en-US", timezone="America/New_York",
extra_prefs=extra_prefs, pin=pin)
def wait_for_condition(page, sample: Callable[[], Any], done: Callable[[Any], Any], what: str, seconds: float = DEADLINE_S) -> Watch:
"""Until ``done(sample())``, reading the page between two looks. Red after ``seconds`` with what was seen on the way."""
result = watch(sample, done, seconds, lambda: page.wait_for_timeout(100))
assert result.ok, "%s; seen: %s" % (what, result.render())
return result
class SecondSession:
"""A session that lives in a thread of its own: ``run(fn)`` calls ``fn(session)`` in that thread and gives back its result or raises its error."""
def __init__(self) -> None:
self._jobs: "queue.Queue[Optional[tuple]]" = queue.Queue()
def run(self, fn: Callable[[Any], Any]) -> Any:
box: Dict[str, Any] = {}
done = threading.Event()
self._jobs.put((fn, box, done))
assert done.wait(300), "the second session did not answer within 300 s"
if "error" in box:
raise box["error"]
return box.get("value")
@contextlib.contextmanager
def in_a_thread_of_its_own(firefox_binary: str, *, extra_prefs: Optional[Dict[str, Any]] = None) -> Iterator[SecondSession]:
"""A second headed session on the same display, started and closed in a thread with no asyncio loop; the test keeps the first one in its own thread."""
handle = SecondSession()
up = threading.Event()
failure: Dict[str, BaseException] = {}
def serve() -> None:
try:
with launch(firefox_binary, extra_prefs=extra_prefs) as session:
up.set()
while True:
job = handle._jobs.get()
if job is None:
return
fn, box, done = job
try:
box["value"] = fn(session)
except BaseException as exc: # handed back to the test's thread by ``run``
box["error"] = exc
finally:
done.set()
except BaseException as exc: # the launch or the close of the session
failure["error"] = exc
finally:
up.set()
worker = threading.Thread(target=serve, name="second-session", daemon=True)
worker.start()
assert up.wait(300), "the second session did not start within 300 s"
if "error" in failure:
raise failure["error"]
try:
yield handle
finally:
handle._jobs.put(None)
worker.join(120)
assert not worker.is_alive(), "the second session did not close within 120 s"
if "error" in failure:
raise failure["error"]
@@ -0,0 +1,81 @@
"""A page keeps the focus when another session takes the display, and loses it only to its own session.
What it fixes: with ``zoom.stealth.focus.ignore_os_deactivation`` (the core declares it true, one value for every session) the window does not give up its
activation when the SYSTEM takes it: another application, or another session's window on the same display. A page reads ``document.hasFocus()`` and the
``blur`` event; without the pref a second visible session made the first one read ``hasFocus()`` false (4 times in 4 on one display) while nothing in its own
session had moved. When the session opens a window of its own the window it replaces is lowered with the blur any Firefox gives.
The hooks: ``AppWindow::WindowDeactivated`` (the early return) and ``AppWindow::WindowActivated`` (``StealthLowerActiveWindow``, which lowers the active window
with its own action id before Mozilla's raise) in ``xpfe/appshell/AppWindow.cpp`` of the series, folder ``fingerprint/screen-window/focus``.
The steps: session A opens a page that records ``focus`` and ``blur``; session B, headed on the same display, opens a window and takes the focus. A's page
still reads ``hasFocus()`` true and has recorded no ``blur``. Then A opens a second page of its own: the first page records its ``blur`` and reads
``hasFocus()`` false, the new one reads it true.
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).
"""
from __future__ import annotations
import pytest
from _window_sessions import in_a_thread_of_its_own, launch, wait_for_condition
pytestmark = pytest.mark.e2e
PREF = "zoom.stealth.focus.ignore_os_deactivation"
RECORD = """() => {
window.__events = [];
for (const type of ['focus', 'blur']) window.addEventListener(type, () => window.__events.push(type));
return document.hasFocus();
}"""
HAS_FOCUS = "() => document.hasFocus()"
EVENTS = "() => window.__events"
TWO_FRAMES = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))"
def takes_the_focus(b):
"""Runs in the second session's own thread: opens a window and waits until its page has the focus."""
taker = b.new_page()
taker.goto("about:blank")
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):
"""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(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")
with in_a_thread_of_its_own(firefox_binary) as b:
b.run(takes_the_focus)
if keeps:
first.evaluate(TWO_FRAMES)
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")
seen = {"has_focus": first.evaluate(HAS_FOCUS), "events": first.evaluate(EVENTS)}
if with_own_page:
own = a.new_page()
own.goto("about:blank")
wait_for_condition(own, lambda: (own.evaluate(HAS_FOCUS), first.evaluate(EVENTS), first.evaluate(HAS_FOCUS)),
lambda state: state[0] is True and state[1].count("blur") == 1 and state[2] is False,
"a page of the session's own did not take the focus from the first with one blur")
seen["after_own_page"] = (own.evaluate(HAS_FOCUS), first.evaluate(EVENTS), first.evaluate(HAS_FOCUS))
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
kept = another_session_takes_the_display(firefox_binary, 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"]
own_focused, events, first_focused = kept["after_own_page"]
assert own_focused is True and events.count("blur") == 1 and first_focused is False, "a page of the session's own did not replace the first one with one blur: %r" % kept
+112
View File
@@ -0,0 +1,112 @@
"""Fullscreen is decided from the declared screen, with no window manager to answer it.
What it fixes: on an X display with no window manager (Xvfb, the way the engine runs on Linux servers) GTK's fullscreen is a request nobody answers, so
Mozilla refuses it: the DOM goes fullscreen and the window does not (``display-mode: fullscreen`` false, ``innerHeight`` the work area). Retail Windows
decides it itself and gives the screen. With the engine active the widget decides it too, from the screen the core declared: after ``requestFullscreen()``
the page reads ``innerWidth x innerHeight`` equal to the declared screen and ``display-mode: fullscreen``.
The hook: ``nsWindow::MakeFullScreen`` in ``widget/gtk/nsWindow.cpp`` of the series, folder ``fingerprint/screen-window/occlusion`` (the marker names
``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 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.
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``.
"""
from __future__ import annotations
import http.server
import sys
import threading
import pytest
from _servers import LocalServer
from _window_sessions import launch, wait_for_condition
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}
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"document.getElementById('go').addEventListener('click', () => {"
b" document.documentElement.requestFullscreen().catch(e => { window.__error = String(e); });"
b"});"
b"</script></body></html>")
GEOMETRY = """() => ({
innerWidth, innerHeight,
screen: [screen.width, screen.height],
displayModeFullscreen: matchMedia('(display-mode: fullscreen)').matches,
fullscreenElement: document.fullscreenElement !== null,
})"""
HOW = "() => [window.__how, window.__error]"
@pytest.fixture
def page_url():
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(PAGE)))
self.end_headers()
self.wfile.write(PAGE)
def log_message(self, *args):
pass
with LocalServer(("127.0.0.1", 0), Handler) as server:
threading.Thread(target=server.serve_forever, daemon=True).start()
try:
yield "http://127.0.0.1:%d/" % server.server_address[1]
finally:
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."""
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:
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:])
# 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))
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
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
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
assert (on["innerWidth"], on["innerHeight"], on["displayModeFullscreen"]) != (off["innerWidth"], off["innerHeight"], off["displayModeFullscreen"])
+76
View File
@@ -0,0 +1,76 @@
"""A window that another one covers stays visible, unless occlusion tracking is enabled.
What it fixes: with ``widget.windows.window_occlusion_tracking.enabled`` and ``zoom.stealth.widget.occlusion_tracking.enabled`` false, as the core declares
them from one value, a page whose window is fully covered by a second window keeps ``document.visibilityState`` ``visible`` and gets no ``visibilitychange``.
Retail Windows with the tracker on says ``hidden`` there (and then throttles ``requestAnimationFrame`` to 1 Hz and the timers to 1000 ms); a session nobody
looks at must not read as backgrounded.
The hook: ``nsWindow::OnVisibilityNotifyEvent`` in ``widget/gtk/nsWindow.cpp`` of the series, folder ``fingerprint/screen-window/occlusion``: the condition of the
ternary that decides ``OCCLUDED`` or ``UNKNOWN`` reads the pref (``StealthOcclusionTracked``). On Windows the same declaration is Mozilla's own pref, so the same
page reading is the proof that the two builds do not disagree.
The control, in the same test: the two prefs true. The same two sessions, the same covering, and the covered page turns ``hidden``. Without it the first half
proves nothing (a window that was never covered is visible too); it runs first, so a runner on which two windows do not cover each other is red here and not a
green that means nothing.
Two sessions are launched on one display and both are headed: the Linux e2e runs under ``xvfb-run`` (no window manager, so the second window is mapped over the
first), Windows uses the interactive desktop of the runner (the second maximized window is created on top of the first and the tracker, when on, calculates
the cover). A page reads it from ``document.visibilityState`` and the ``visibilitychange`` event.
"""
from __future__ import annotations
import pytest
from _window_sessions import in_a_thread_of_its_own, launch, wait_for_condition
pytestmark = pytest.mark.e2e
#: The one decision, under both engine names (core: ``OCCLUSION_TRACKING``).
TRACKING_PREFS = ("widget.windows.window_occlusion_tracking.enabled", "zoom.stealth.widget.occlusion_tracking.enabled")
#: Records every change of visibility of the document, and answers the current state.
WATCH = """() => {
window.__visibility = [document.visibilityState];
document.addEventListener('visibilitychange', () => window.__visibility.push(document.visibilityState));
return document.visibilityState;
}"""
STATE = "() => document.visibilityState"
CHANGES = "() => window.__visibility"
#: Two painted frames: the page's own process has handled what the window system told it before this returns.
TWO_FRAMES = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))"
def opens_the_covering_window(second):
"""Runs in the second session's own thread: opens a window on the display and waits for two painted frames."""
cover = second.new_page()
cover.goto("about:blank")
cover.evaluate(TWO_FRAMES)
def second_window_over_the_first(firefox_binary, tracking):
"""(state, changes) of the first session's page after a second session's window is up over it.
``tracking`` is None for the product as it launches, or the value both tracking prefs are given."""
extra = None if tracking is None else {name: tracking for name in TRACKING_PREFS}
with launch(firefox_binary, extra_prefs=extra) as first, in_a_thread_of_its_own(firefox_binary) as second:
covered = first.new_page()
covered.goto("about:blank")
assert covered.evaluate(WATCH) == "visible", "the page was not visible before anything covered it"
second.run(opens_the_covering_window)
if tracking:
wait_for_condition(covered, lambda: covered.evaluate(STATE), lambda state: state == "hidden",
"a window that another one covers never turned hidden with occlusion tracking enabled")
else:
covered.evaluate(TWO_FRAMES)
return covered.evaluate(STATE), covered.evaluate(CHANGES)
def test_a_covered_window_stays_visible_unless_occlusion_tracking_is_enabled(firefox_binary):
tracked_state, tracked_changes = second_window_over_the_first(firefox_binary, True)
assert tracked_state == "hidden" and tracked_changes == ["visible", "hidden"], (
"control: with tracking enabled the covered page reads %r, changes %r" % (tracked_state, tracked_changes))
state, changes = second_window_over_the_first(firefox_binary, None)
assert state == "visible" and changes == ["visible"], (
"the product's covered page reads %r, changes %r: it must stay visible, with no visibilitychange" % (state, changes))
assert state != tracked_state, "enabled and disabled read the same: the declaration decides nothing"