Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bcd945e985 | ||
|
|
0a3a2e5ba3 |
@@ -19,6 +19,15 @@ its process: only the back-forward cache can end the worker, which is the case J
|
||||
another site (with strategy 1 the top changes process), by `page.goto` (Page.navigate gives the top a new browsing
|
||||
context even on the same site) or by the page's own `location.href` (the same browsing context). Hosts a.test / b.test / c.test resolve to one local server
|
||||
(`network.dns.localDomains`): two hosts are two sites, one port.
|
||||
|
||||
THE PRECONDITION IS FIREFOX'S, NOT OURS. Whether a document goes into the back-forward cache is Firefox's decision, taken when the
|
||||
next navigation starts (nsDocShell::InternalLoad -> Document::CanSavePresentation, CanonicalBrowsingContext::AllowedInBFCache), and
|
||||
a document that is refused is refused for good: it is loaded again on the way back. What refuses it is anything in flight in the
|
||||
document's load group at that moment (a dedicated worker's script fetch is one: a worker that has not started yet makes the page
|
||||
non-restorable, measured 0 of 8 restored when leaving right after `load`, 8 of 8 after one round trip to the worker) and the
|
||||
page's `pageshow` not yet run (it clears the loading mark). So the test leaves only when every document it holds has had its
|
||||
`pageshow` and its worker has answered, and a run whose page was still loaded again is not a result of ours: the gesture is
|
||||
repeated on a fresh browser, up to ATTEMPTS times, and only ATTEMPTS refusals in a row fail, loudly.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -30,6 +39,20 @@ import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
#: How many times the whole gesture may be started again because Firefox did not put the page in the cache (see above).
|
||||
ATTEMPTS = 3
|
||||
|
||||
|
||||
#: More repeated gestures than this in one run of this file and the cache is refusing too often: the run fails, naming them.
|
||||
MOST_REFUSALS_IN_A_RUN = 2
|
||||
#: Every refusal of Firefox met by `_until_restored`, in this process, in order.
|
||||
REFUSALS = []
|
||||
|
||||
|
||||
class _NotRestored(Exception):
|
||||
"""Firefox loaded the page again instead of restoring it: the precondition of the test, not a verdict on it."""
|
||||
|
||||
|
||||
STRATEGY_1 = {
|
||||
"fission.autostart": True,
|
||||
"fission.webContentIsolationStrategy": 1,
|
||||
@@ -89,8 +112,12 @@ def sites():
|
||||
"<script>window.__shown = []; addEventListener('pageshow', e => window.__shown.push(e.persisted));"
|
||||
"</script><iframe id=f src='%s' width=300 height=150></iframe>" % at("b.test", "/frame-worker"))
|
||||
routes["/other"] = ("text/html", "<!doctype html><title>other</title><p>other")
|
||||
routes["/top-plain"] = ("text/html", "<!doctype html><title>plain</title>"
|
||||
"<script>window.__shown = []; addEventListener('pageshow', e => window.__shown.push(e.persisted));"
|
||||
"</script><p>no worker here")
|
||||
try:
|
||||
yield {"top": {"page": at("a.test", "/top-worker")}, "oop-frame": {"page": at("a.test", "/top-frame")},
|
||||
"plain": at("a.test", "/top-plain"),
|
||||
"same-site": at("a.test", "/other"), "other-site": at("c.test", "/other")}
|
||||
finally:
|
||||
server.shutdown()
|
||||
@@ -129,6 +156,15 @@ def _index(events, start, method, pred=lambda p: True):
|
||||
return None
|
||||
|
||||
|
||||
def _wait_cacheable(page):
|
||||
"""Until every document of the page that records `pageshow` has had it: a document whose `load` handlers are still running,
|
||||
or whose `pageshow` has not run, is still marked as loading and Firefox will not cache it (Document::OnPageShow clears
|
||||
the mark). The worker's own start is the round trips the caller made before."""
|
||||
def shown():
|
||||
return all(frame.evaluate("(window.__shown || [0]).length >= 1") for frame in page.frames)
|
||||
assert _wait(shown, 10.0), "a document of the page never ran its pageshow: %r" % [f.url for f in page.frames]
|
||||
|
||||
|
||||
def _ask(page, where):
|
||||
target = page if where == "top" else next(f for f in page.frames if f.url.endswith("/frame-worker"))
|
||||
return target.evaluate("window.__ask()")
|
||||
@@ -141,6 +177,54 @@ def _ask(page, where):
|
||||
def test_a_worker_leaves_with_its_page_for_the_cache_and_comes_back_the_same(firefox_binary, sites, events, where,
|
||||
away, how, engine_at_least):
|
||||
engine_at_least("firefox-62")
|
||||
|
||||
def attempt():
|
||||
del events[:] # the events of this attempt only: the ids and the order are read from them
|
||||
_gesture(firefox_binary, sites, events, where, away, how)
|
||||
|
||||
_until_restored(attempt)
|
||||
|
||||
|
||||
def _until_restored(attempt, attempts=ATTEMPTS, record=None):
|
||||
"""Run `attempt` until Firefox has put the page in the cache. A verdict of ours (any other failure) ends it at once."""
|
||||
record = REFUSALS if record is None else record # the unit test of this loop keeps its own: it is not a refusal of Firefox
|
||||
refused = []
|
||||
for _ in range(attempts):
|
||||
try:
|
||||
attempt()
|
||||
return
|
||||
except _NotRestored as why:
|
||||
refused.append(str(why))
|
||||
record.append(str(why))
|
||||
print("\n[bfcache] the page was refused by the cache (%d so far in this run): %s" % (len(record), why))
|
||||
raise AssertionError(
|
||||
"Firefox did not put the page in the back-forward cache in %d attempts out of %d, so this test proves nothing: %r"
|
||||
% (len(refused), attempts, refused))
|
||||
|
||||
|
||||
def test_a_refused_page_is_tried_again_and_only_attempts_refusals_in_a_row_fail():
|
||||
calls = []
|
||||
|
||||
def refused_twice():
|
||||
calls.append(1)
|
||||
if len(calls) < ATTEMPTS:
|
||||
raise _NotRestored("loaded again")
|
||||
|
||||
_until_restored(refused_twice, record=[])
|
||||
assert len(calls) == ATTEMPTS
|
||||
|
||||
calls.clear()
|
||||
with pytest.raises(AssertionError, match="proves nothing"):
|
||||
_until_restored(lambda: (calls.append(1), (_ for _ in ()).throw(_NotRestored("loaded again"))), record=[])
|
||||
assert len(calls) == ATTEMPTS
|
||||
|
||||
calls.clear() # a verdict of ours is not retried
|
||||
with pytest.raises(ValueError):
|
||||
_until_restored(lambda: (calls.append(1), (_ for _ in ()).throw(ValueError("ours"))), record=[])
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def _gesture(firefox_binary, sites, events, where, away, how):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False,
|
||||
@@ -159,6 +243,7 @@ def test_a_worker_leaves_with_its_page_for_the_cache_and_comes_back_the_same(fir
|
||||
"the frame of the worker is not listed with its url: %r" % [f.url for f in page.frames])
|
||||
assert _ask(page, where) == 1
|
||||
assert _ask(page, where) == 2
|
||||
_wait_cacheable(page)
|
||||
|
||||
# 2. the top goes forward: the worker ends for the client, before the new page commits
|
||||
forward = len(events)
|
||||
@@ -176,8 +261,8 @@ def test_a_worker_leaves_with_its_page_for_the_cache_and_comes_back_the_same(fir
|
||||
# 3. back from the cache: the same worker, told once, after the restored document's contexts are cleared
|
||||
back = len(events)
|
||||
page.go_back(wait_until="load")
|
||||
assert page.evaluate("window.__shown") == [False, True], (
|
||||
"the page was loaded again instead of restored from the back-forward cache, so this test proves nothing")
|
||||
if page.evaluate("window.__shown") != [False, True]:
|
||||
raise _NotRestored("the page was loaded again instead of restored: __shown = %r" % page.evaluate("window.__shown"))
|
||||
if not _wait(lambda: _index(events, back, "Page.workerCreated", lambda p: p["workerId"] == wid) is not None):
|
||||
other = [p["workerId"] for m, p in events[back:] if m == "Page.workerCreated"]
|
||||
raise AssertionError(("the restored worker was announced under a NEW id %s, not %s: " % (other, wid)
|
||||
@@ -213,3 +298,59 @@ def _methods(events, start):
|
||||
for m, p in events[start:] if m.startswith(("Page.worker", "Page.navigationCommitted", "Page.frameDocument",
|
||||
"Runtime.executionContextsCleared", "Page.frameDetached",
|
||||
"Page.frameAttached"))]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def the_cache_does_not_refuse_too_often():
|
||||
"""A repeated gesture hides a refusal of Firefox, and a regression of the cache would hide the same way: so the repeats are
|
||||
counted over the whole file, printed, and more than MOST_REFUSALS_IN_A_RUN of them fail the run, loudly."""
|
||||
del REFUSALS[:]
|
||||
yield
|
||||
print("\n[bfcache] refusals met in this run: %d (at most %d allowed)" % (len(REFUSALS), MOST_REFUSALS_IN_A_RUN))
|
||||
assert len(REFUSALS) <= MOST_REFUSALS_IN_A_RUN, (
|
||||
"the back-forward cache refuses too often: %d gestures had to be repeated in one run (at most %d): %r"
|
||||
% (len(REFUSALS), MOST_REFUSALS_IN_A_RUN, REFUSALS))
|
||||
|
||||
|
||||
def _leave_and_come_back(page, away_url):
|
||||
"""Leave the page at once (no wait of any kind) and come back: what the page recorded of its own `pageshow`."""
|
||||
page.goto(away_url, wait_until="load")
|
||||
page.go_back(wait_until="load")
|
||||
return page.evaluate("window.__shown")
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_page_without_a_worker_comes_back_from_the_cache(firefox_binary, sites, engine_at_least):
|
||||
"""No repeat, no wait: the cache has to take a plain page the moment it has loaded. If the cache breaks, this one says so."""
|
||||
engine_at_least("firefox-62")
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False,
|
||||
headless=True, extra_prefs=STRATEGY_1) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.set_default_timeout(10000)
|
||||
page.goto(sites["plain"], wait_until="load")
|
||||
assert _leave_and_come_back(page, sites["same-site"]) == [False, True], (
|
||||
"a page with no worker was loaded again instead of restored from the back-forward cache")
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_page_whose_started_worker_is_in_a_frame_of_another_site_comes_back_from_the_cache(firefox_binary, sites, engine_at_least):
|
||||
"""No repeat: a page with a started worker in a frame of another site (its own process) is taken by the cache. The worker is
|
||||
asked once first, because a worker that has not started keeps ANY page out of the cache (its script fetch is in the load group:
|
||||
leaving right after the frame is listed, 0 of 2 restored here). If the cache breaks for pages with frames in other processes,
|
||||
this one says so."""
|
||||
engine_at_least("firefox-62")
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False,
|
||||
headless=True, extra_prefs=STRATEGY_1) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.set_default_timeout(10000)
|
||||
page.goto(sites["oop-frame"]["page"], wait_until="load")
|
||||
assert _wait(lambda: any(f.url.endswith("/frame-worker") for f in page.frames)), (
|
||||
"the frame of the worker is not listed with its url: %r" % [f.url for f in page.frames])
|
||||
assert _ask(page, "oop-frame") == 1
|
||||
_wait_cacheable(page)
|
||||
assert _leave_and_come_back(page, sites["same-site"]) == [False, True], (
|
||||
"a page with a worker in a frame of another site was loaded again instead of restored from the back-forward cache")
|
||||
Reference in new issue
Block a user