A popup is reported on Page.ready as Playwright's is: no limit and no warning, with the address of the commit that came with the ready
- Stock Playwright 1.62 (measured): a 204 or a silent destination gives no page event, one that answers after 4 s gives it at 4 s with the
destination already. The adoption of a popup waited 20 s and dropped it with a warning; now only a page a caller asked for
(newPage) has the 20 s; a popup waits until the engine says Page.ready, the target goes away, or its context closes
(BrowserDispatcher.end_waits_of), and says nothing.
- The ready and the commit of the document that made the page ready come in the same turn: the page is announced after a round trip to the
engine (settle_events), so the frame reads the destination at the page event (3 of 4 slow popups said about:blank).
- In-process the slow popup arrived 0.9 s later than stock: it is the humanised click (1.1 s of pointer movement before the click returns),
the popup arrives 4.02 s after the click in both modes.
- Tests: unit (limit None for a popup and 20 s for a requested page; a popup with no ready ends with its context and says nothing; the
address at the page event is the commit's) red on b09d620; e2e (204 and silent: no event; 1.5 s: url is the destination; 25 s: reported
then) in-process and through a served browser: the 25 s ones red on b09d620.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b09d620930
commit
fbceeafb65
5 files changed
+290
-4
No files matched your search
@@ -2799,6 +2799,13 @@ class PageDispatcher(Dispatcher):
|
||||
"""
|
||||
self.lifecycle.wait_for_page_ready(timeout=timeout)
|
||||
|
||||
def settle_events(self) -> None:
|
||||
"""Return once every event the engine sent before this call has been handled: its reply comes after them, on one stream."""
|
||||
try:
|
||||
self.conn.send("Browser.getInfo", {}, timeout=5.0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _install_events(self) -> None:
|
||||
"""Turn Juggler events into protocol events.
|
||||
|
||||
@@ -4381,6 +4388,7 @@ class BrowserContextDispatcher(Dispatcher):
|
||||
# whose only context it is. `Browser.removeBrowserContext` on it
|
||||
# would make Juggler's `destroy()` unregister the default from its
|
||||
# maps and leave a browser that no command can address.
|
||||
self.browser.end_waits_of(self)
|
||||
for page in list(self.pages):
|
||||
try:
|
||||
page.announce_closed()
|
||||
@@ -4403,6 +4411,7 @@ class BrowserContextDispatcher(Dispatcher):
|
||||
# sets `is_closed()` and fires `page.on("close")` from that event, so
|
||||
# a page belonging to a closed context stayed "open" forever, and any
|
||||
# code waiting for it to close waited for good.
|
||||
self.browser.end_waits_of(self)
|
||||
for page in list(self.pages):
|
||||
try:
|
||||
page.announce_closed()
|
||||
@@ -4759,6 +4768,12 @@ class BrowserDispatcher(Dispatcher):
|
||||
how it was opened. Stealth is preserved by doing nothing special.
|
||||
"""
|
||||
page = None
|
||||
# ⛔ A PAGE A CALLER ASKED FOR (`Browser.newPage`) WAITS AT MOST 20 s FOR ITS Page.ready, AND FAILS LOUDLY; A POPUP WAITS AS LONG
|
||||
# AS THE ENGINE TAKES, AND SAYS NOTHING. That is Playwright's own: its popup is reported on Page.ready and not before, with no
|
||||
# limit - a destination that answers 204 or never answers gives no `page` event at all (measured, stock Playwright 1.62 and its
|
||||
# Firefox: none in 30 s), one that answers after 25 s gives it at 25 s. The wait ends when the target goes away or its context
|
||||
# closes.
|
||||
requested = number is None
|
||||
try:
|
||||
if number is None:
|
||||
number = self._number_of_requested(
|
||||
@@ -4769,15 +4784,29 @@ class BrowserDispatcher(Dispatcher):
|
||||
number, opener=opener)
|
||||
with self._targets_lock:
|
||||
self._building[target_id] = page
|
||||
gone = False
|
||||
try:
|
||||
page.wait_until_ready(timeout=20.0)
|
||||
page.wait_until_ready(timeout=20.0 if requested else None)
|
||||
except juggler.TargetClosedError:
|
||||
# Gone before it was ready (a popup the site closed at once): announced and closed right after, as a detach that
|
||||
# beats the adoption always was (`_detached_early`).
|
||||
pass
|
||||
# Gone before it was ready (a download's empty tab, a popup the site closed at once): announced and closed right
|
||||
# after, as Playwright's is and as a detach that beats the adoption always was (`_detached_early`).
|
||||
gone = True
|
||||
finally:
|
||||
with self._targets_lock:
|
||||
self._building.pop(target_id, None)
|
||||
if gone and not requested and context.disposed:
|
||||
# Its context closed while it waited for a ready that never came: it was never announced and is not now.
|
||||
page.announce_closed()
|
||||
with self._targets_lock:
|
||||
self._adopting.discard(target_id)
|
||||
self._detached_early.discard(target_id)
|
||||
self._pages_ready.notify_all()
|
||||
return
|
||||
# ⛔ THE EVENTS THAT COME WITH THE READY ARE APPLIED FIRST. The engine says Page.ready and, in the same turn, the commit of
|
||||
# the document that made the page ready: announced between the two, the page tells its client `about:blank` (3 of 4 popups
|
||||
# to a slow destination, measured) where Playwright's says the destination. A round trip to the engine comes back after
|
||||
# everything it sent before it.
|
||||
page.settle_events()
|
||||
# ⛔ `page` BEFORE the registration, on purpose. A detach racing
|
||||
# this build is recorded as early (see `_handle_detach`) and the
|
||||
# close is announced right after, so the client always sees the
|
||||
@@ -4864,6 +4893,16 @@ class BrowserDispatcher(Dispatcher):
|
||||
"Browser.attachedToTarget for it" % (target_id, timeout))
|
||||
self._pages_ready.wait(left)
|
||||
|
||||
def end_waits_of(self, context: "BrowserContextDispatcher") -> None:
|
||||
"""A context is closing: the popups of it that are still waiting for a Page.ready that never came stop waiting."""
|
||||
with self._targets_lock:
|
||||
waiting = [p for p in self._building.values() if p.context is context]
|
||||
for page in waiting:
|
||||
try:
|
||||
page.lifecycle.detach()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _handle_detach(self, target_id: Optional[str],
|
||||
session_id: Optional[str]) -> None:
|
||||
"""The engine reports a target gone: an engine-side close (or a popup
|
||||
|
||||
@@ -59,6 +59,9 @@ class _Page:
|
||||
def wait_until_ready(self, timeout=20.0):
|
||||
pass # the engine of this test says Page.ready at once
|
||||
|
||||
def settle_events(self):
|
||||
pass
|
||||
|
||||
def announce_closed(self):
|
||||
pass
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ class LateReadyJuggler(ScriptedJuggler):
|
||||
super().__init__()
|
||||
self.held = {}
|
||||
self.released = set()
|
||||
self.queued = []
|
||||
|
||||
def dispatch_event(self, method, params, session=None):
|
||||
if method == "Page.ready" and session not in self.released:
|
||||
@@ -46,6 +47,15 @@ class LateReadyJuggler(ScriptedJuggler):
|
||||
return None
|
||||
return super().dispatch_event(method, params, session)
|
||||
|
||||
def send(self, method, params=None, session=None, timeout=30):
|
||||
if method == "Browser.getInfo":
|
||||
# a reply comes after everything the engine sent before it: the events queued as "sent with the ready" arrive first
|
||||
queued, self.queued = self.queued, []
|
||||
for event, event_params, event_session in queued:
|
||||
super().dispatch_event(event, event_params, event_session)
|
||||
return {}
|
||||
return super().send(method, params, session, timeout)
|
||||
|
||||
def say_ready(self, session):
|
||||
self.released = set(self.released) | {session}
|
||||
method, params = self.held.pop(session)
|
||||
@@ -209,3 +219,87 @@ def test_what_a_popup_does_before_its_ready_reaches_its_frame(late_browser, monk
|
||||
if fid == frame_id and event == "loadstate" and params and "add" in params}
|
||||
assert "load" in heard, ("the client's frame never heard `load` of the popup (heard %s): wait_for_url(until=load) would wait for ever"
|
||||
% sorted(heard))
|
||||
|
||||
|
||||
def test_a_popup_waits_for_its_ready_without_a_limit_and_a_requested_page_for_twenty_seconds(late_browser, monkeypatch):
|
||||
"""Playwright's popup is reported on Page.ready with no limit (a destination that answers after 25 s gives the event at 25 s); the
|
||||
page a caller asked for waits 20 s and fails."""
|
||||
from invisible_playwright._juggler.server import PageDispatcher
|
||||
waited = []
|
||||
original = PageDispatcher.wait_until_ready
|
||||
|
||||
def spy(self, timeout=20.0):
|
||||
waited.append(timeout)
|
||||
return original(self, timeout)
|
||||
|
||||
monkeypatch.setattr(PageDispatcher, "wait_until_ready", spy)
|
||||
server, conn = late_browser.server, late_browser.conn
|
||||
context = _new_context(late_browser)
|
||||
conn.released = {"s1"}
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(iter(conn.sessions))
|
||||
conn.popup_born(opener_target, context.context_id, 1)
|
||||
deadline = time.monotonic() + 5
|
||||
while len(waited) < 2 and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert waited == [20.0, None], "a requested page waits 20 s, a popup without a limit: %r" % (waited,)
|
||||
|
||||
|
||||
def test_a_popup_that_never_gets_its_ready_ends_with_its_context_and_says_nothing(late_browser):
|
||||
"""204, a server that never answers: no ready, no `page` event, no warning; closing the context ends the wait."""
|
||||
import warnings
|
||||
server, conn = late_browser.server, late_browser.conn
|
||||
context = _new_context(late_browser)
|
||||
conn.released = {"s1"}
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(iter(conn.sessions))
|
||||
announced = []
|
||||
original = context.emit
|
||||
context.emit = lambda event, params=None: (announced.append(event) if event == "page" else None, original(event, params))[1]
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
conn.popup_born(opener_target, context.context_id, 1)
|
||||
time.sleep(0.5)
|
||||
assert not announced, "a popup with no ready was announced"
|
||||
assert late_browser._building, "the popup is not waiting"
|
||||
server.handle({"guid": context.guid, "method": "close", "params": {}})
|
||||
deadline = time.monotonic() + 5
|
||||
while late_browser._building and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert not late_browser._building, "closing the context did not end the wait of the popup"
|
||||
time.sleep(0.2)
|
||||
assert not announced, "a popup of a closed context was announced"
|
||||
assert not [w for w in caught if "adoption" in str(w.message)], [str(w.message) for w in caught]
|
||||
|
||||
|
||||
def test_a_popup_is_announced_with_the_address_of_the_commit_that_came_with_its_ready(late_browser):
|
||||
"""The engine says Page.ready and, in the same turn, the commit of the document: the client is told the page after the commit, so
|
||||
the url it reads at the `page` event is the destination, as Playwright's is (3 of 4 popups said about:blank)."""
|
||||
server, conn = late_browser.server, late_browser.conn
|
||||
context = _new_context(late_browser)
|
||||
conn.released = {"s1"}
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(iter(conn.sessions))
|
||||
urls = []
|
||||
original = context.emit
|
||||
|
||||
def spy(event, params=None):
|
||||
if event == "page":
|
||||
page = next(o for o in server._objects.values() if o.TYPE == "Page" and o.channel == params["page"])
|
||||
urls.append(page.frame.url)
|
||||
return original(event, params)
|
||||
|
||||
context.emit = spy
|
||||
target, session = conn.popup_born(opener_target, context.context_id, 1)
|
||||
frame_id = "f" + target
|
||||
url = "http://127.0.0.1/slow"
|
||||
deadline = time.monotonic() + 5
|
||||
while not any(o.TYPE == "Page" and getattr(o, "session", None) == session for o in server._objects.values()) and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
conn.queued.append(("Page.navigationStarted", {"frameId": frame_id, "navigationId": "n1", "url": url}, session))
|
||||
conn.queued.append(("Page.navigationCommitted", {"frameId": frame_id, "navigationId": "n1", "url": url, "name": ""}, session))
|
||||
conn.say_ready(session) # the commit follows in the stream: it is delivered with the round trip that comes back after it
|
||||
deadline = time.monotonic() + 5
|
||||
while not urls and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert urls == [url], "the popup was announced with %r, not with the address of the commit that came with its ready" % (urls,)
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
"""A popup is reported on Page.ready, as Playwright's own is: with no limit, and with the destination's address already.
|
||||
|
||||
Measured against stock Playwright 1.62 and its Firefox (in-process, 2 runs of each, never in disagreement):
|
||||
* a destination that answers 204, or never answers: NO `page` event in 30 s (nothing commits, the engine never says Page.ready);
|
||||
* a destination that answers after 4 s: the event at 4.08 s, with `url` already the destination and `load` in the same millisecond.
|
||||
Here: the same two, in-process and through a served browser driven by a stock client, and a destination that answers after 25 s (the
|
||||
wrapper dropped a popup that was not ready in 20 s, with a warning); the address read at the `page` event is the destination.
|
||||
|
||||
Red on b09d620: the popup of the slow destination reads `about:blank` at the event (the commit comes in the same turn as the ready and
|
||||
was applied after the page was announced), and the one that answers after 25 s was dropped at 20 s.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
|
||||
import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
|
||||
class _Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
path, _, query = self.path.partition("?")
|
||||
if path == "/nocontent":
|
||||
self.send_response(204)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
if path == "/slow":
|
||||
ms = int(query.split("ms=")[1].split("&")[0]) if "ms=" in query else 0
|
||||
time.sleep(ms / 1000.0)
|
||||
body = b"<!doctype html><html><head><title>slow</title></head><body>slow</body></html>"
|
||||
else:
|
||||
body = (b"<!doctype html><html><head><title>opener</title></head><body>"
|
||||
b"<button id=open204 onclick=\"window.open('/nocontent','_blank')\">open</button>"
|
||||
b"<a id=link204 href=/nocontent target=_blank>link</a>"
|
||||
b"<button id=open1500 onclick=\"window.open('/slow?ms=1500','_blank')\">open</button>"
|
||||
b"<a id=link1500 href='/slow?ms=1500' target=_blank>link</a>"
|
||||
b"<button id=open25000 onclick=\"window.open('/slow?ms=25000','_blank')\">open</button>"
|
||||
b"</body></html>")
|
||||
try:
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
except OSError: # the browser left before a slow answer
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def site():
|
||||
srv = LocalServer(("127.0.0.1", 0), _Handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
try:
|
||||
yield "http://127.0.0.1:%d/" % srv.server_address[1]
|
||||
finally:
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
def _stock_client(module):
|
||||
import importlib
|
||||
|
||||
try:
|
||||
return importlib.import_module(module)
|
||||
except ImportError as exc: # pragma: no cover - only in a broken environment
|
||||
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc, pytrace=False)
|
||||
|
||||
|
||||
def _drive(mode, firefox_binary, body):
|
||||
"""Run body(context, page) in-process or through a served browser driven by a stock client."""
|
||||
if mode == "in-process":
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, humanize=False) as b:
|
||||
ctx = b.new_context()
|
||||
body(ctx, ctx.new_page())
|
||||
ctx.close()
|
||||
return
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
sync_playwright = _stock_client("playwright.sync_api").sync_playwright
|
||||
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.connect(server.ws_endpoint)
|
||||
ctx = browser.new_context()
|
||||
body(ctx, ctx.new_page())
|
||||
ctx.close()
|
||||
browser.close()
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
MODES = ["in-process", "served"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", MODES)
|
||||
@pytest.mark.parametrize("opener", ["#open204", "#link204"])
|
||||
def test_a_destination_that_commits_nothing_gives_no_popup_event(firefox_binary, site, mode, opener):
|
||||
def body(ctx, page):
|
||||
page.goto(site, wait_until="load", timeout=30000)
|
||||
seen = []
|
||||
ctx.on("page", lambda p: seen.append(p))
|
||||
page.click(opener)
|
||||
time.sleep(6)
|
||||
assert not seen, "a popup whose destination commits nothing was reported (Playwright's is not)"
|
||||
assert len(ctx.pages) == 1
|
||||
|
||||
_drive(mode, firefox_binary, body)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", MODES)
|
||||
@pytest.mark.parametrize("opener", ["#open1500", "#link1500"])
|
||||
def test_a_slow_popup_is_reported_with_the_address_of_its_destination(firefox_binary, site, mode, opener):
|
||||
def body(ctx, page):
|
||||
page.goto(site, wait_until="load", timeout=30000)
|
||||
with page.expect_popup(timeout=20000) as info:
|
||||
page.click(opener)
|
||||
assert info.value.url == site + "slow?ms=1500", "the popup was reported with %r" % info.value.url
|
||||
info.value.close()
|
||||
|
||||
_drive(mode, firefox_binary, body)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", MODES)
|
||||
def test_a_popup_whose_destination_answers_after_25_seconds_is_reported_then(firefox_binary, site, mode):
|
||||
def body(ctx, page):
|
||||
page.goto(site, wait_until="load", timeout=30000)
|
||||
t0 = time.monotonic()
|
||||
with page.expect_popup(timeout=45000) as info:
|
||||
page.click("#open25000")
|
||||
took = time.monotonic() - t0
|
||||
assert 24.0 < took < 40.0, "reported after %.1f s" % took
|
||||
assert info.value.url == site + "slow?ms=25000"
|
||||
info.value.close()
|
||||
|
||||
_drive(mode, firefox_binary, body)
|
||||
@@ -240,6 +240,9 @@ class _Page:
|
||||
def wait_until_ready(self, timeout=20.0):
|
||||
pass # the engine of this test says Page.ready at once
|
||||
|
||||
def settle_events(self):
|
||||
pass
|
||||
|
||||
def announce_closed(self):
|
||||
pass
|
||||
|
||||
|
||||
Reference in new issue
Block a user