Compare commits

...
Author SHA1 Message Date
feder-crandClaude Fable 5.2 e508063cd4 tests: the relay page waits for the frame it writes to
The two sibling frames load in two processes, in no fixed order. The top page
relayed the first frame's message at once, and when the second frame's document
was not there yet the message was lost, as it would be in any browser: one CI
run in three never saw the answer. The top now holds a message until the load
event of the frame it is for.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 06:05:52 +01:00
feder-crandClaude Sonnet 5.5 7fd63cf786 tests: the cross-site iframe proof reads the frame after the page's load, not its domcontentloaded
The domcontentloaded of a page says nothing about its frames: the url of a frame of another site is
the url of its navigation, which commits in the frame's own process, usually after it. Read straight
after a domcontentloaded goto the url was empty in 26 of 30 reads on firefox-62 and in 5 of 21 runs of
the test; after the load of the page it was there 30 of 30, on stock Firefox too. The test now goes to
the page with the default load and asserts the url with no wait.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:31:16 +01:00
feder-crandClaude Fable 5.2 820b350e4e tests: the frame of B reads its own partition, not an empty one
The reverse half of the partition test expected an empty cookie string in the
frame of B inside A. The frame has its own partition, and the two cookies it
wrote earlier in the test are in it: what must be absent is what B wrote as a
top page. The first CI run showed it; the first half already passed there.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 03:25:09 +01:00
feder-crandClaude Sonnet 5.5 1bff8ecede tests: site B's storage is partitioned between a frame of A and B as a top page (retail outcome)
The reference for what a page reads is retail Firefox, which partitions cookies and storage by
top-level site; Playwright's own Firefox has that off. The test now asserts that B opened as a top
page sees an empty document.cookie and a null localStorage item for what B wrote inside a frame of A
(context.cookies() still lists B's cookies), and the reverse.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 02:51:40 +01:00
feder-crandClaude Sonnet 5.5 9e70126edb tests: end-to-end tests for iframes under Fission, and a cross-site harness for the cross-origin file
New files hold the gaps of the frame tests, each with a proof that the frame is in another
process: the frame tree A > B > A > C, typing and waits, clicks under a transform and after
scrolling, screenshots; routes, exposed functions, init scripts, postMessage; dialogs,
downloads and popups started in a frame; workers, storage and special frames; history and
processes left behind by a closed context. tests/_fission_frames.py holds the three sites
(127.0.0.1, localhost, 127.0.0.2) and the process proof they share.

test_cross_origin_iframe.py now serves its iframes from localhost while the page stays on
127.0.0.1 (two ports of one host are one site and never crossed a process), and proves it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 02:45:39 +01:00
7 changed files with 1709 additions and 19 deletions

No files matched your search

+243
View File
@@ -0,0 +1,243 @@
"""What the Fission frame tests (`test_fission_frames_*_e2e.py`) share: three sites, and a proof of a process.
Three SITES on one machine, told apart by HOST and never by port (`127.0.0.1:1` and `127.0.0.1:2` are one site,
so a frame served from the other port stays in the process of its page):
A 127.0.0.1 the top page, and the A inside A > B > A > C
B localhost the iframe of another site
C 127.0.0.2 the third site
The wrapper runs Fission the way retail Firefox does (strategy 1, one content process per site), so with no pref a
frame of B inside a page of A runs in another process.
`assert_other_process` is how a test proves that, from inside the pages and with no help from the driver: the
frame spins for 600 ms and the observer frame times a 10 ms timer, which stalls only when the two share a process.
A test file calls it at least once, so the suite cannot silently turn into a same-process suite.
"""
from __future__ import annotations
import json
import struct
import threading
import zlib
import time
from http.server import BaseHTTPRequestHandler
from urllib.parse import parse_qs, urlsplit
from _servers import LocalServer
HOSTS = {"A": "127.0.0.1", "B": "localhost", "C": "127.0.0.2"}
#: How long the frame keeps its main thread busy, and the longest gap of the observer's timer that still means
#: "another process" (a process shared with the frame is stalled for about the whole spin).
SPIN_MS = 600
OWN_PROCESS_GAP_MS = 300
HTML = "text/html; charset=utf-8"
class Sites:
"""Three local servers, one per site, and the routes they serve.
``route(site, path, body, ...)`` registers a page; ``body`` is a string or bytes, or a function of the request
that returns the same (the request is the handler: ``.headers``, ``.query``). ``requests`` lists what arrived,
as dicts with ``site``, ``path``, ``query``, ``method`` and ``headers``.
"""
def __init__(self):
self._routes = {}
self.requests = []
self.servers = {}
self.origin = {}
sites = self
class Handler(BaseHTTPRequestHandler):
timeout = 10
def log_message(self, *args):
pass
def _answer(self):
url = urlsplit(self.path)
self.query = parse_qs(url.query)
site = self.server.site
length = int(self.headers.get("Content-Length") or 0)
self.body = self.rfile.read(length) if length else b""
sites.requests.append({"site": site, "path": url.path, "query": self.query,
"method": self.command, "headers": dict(self.headers)})
spec = sites._routes.get((site, url.path))
if spec is None:
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
return
body = spec["body"](self) if callable(spec["body"]) else spec["body"]
if isinstance(body, str):
body = body.encode("utf-8")
if spec["delay"]:
time.sleep(spec["delay"])
try:
self.send_response(spec["status"])
self.send_header("Content-Type", spec["ctype"])
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
for name, value in spec["headers"]:
self.send_header(name, value)
self.end_headers()
self.wfile.write(body)
except OSError:
pass
do_GET = _answer
do_POST = _answer
self._handler = Handler
def __enter__(self):
for site, host in HOSTS.items():
server = LocalServer((host if host != "localhost" else "127.0.0.1", 0), self._handler)
server.site = site
threading.Thread(target=server.serve_forever, daemon=True).start()
self.servers[site] = server
self.origin[site] = "http://%s:%d" % (host, server.server_address[1])
return self
def __exit__(self, *exc):
for server in self.servers.values():
server.shutdown()
server.server_close()
def url(self, site, path=""):
return self.origin[site] + path
def route(self, site, path, body, ctype=HTML, status=200, headers=(), delay=0):
self._routes[(site, path)] = {"body": body, "ctype": ctype, "status": status,
"headers": list(headers), "delay": delay}
def seen(self, site, path):
return [r for r in self.requests if r["site"] == site and r["path"] == path]
def wait_for(page, predicate, seconds=10.0):
"""Until ``predicate()``, with the client's events being read (the sync client takes the engine's events only
inside its own calls, so a plain sleep would never see a frame arrive)."""
end = time.monotonic() + seconds
while time.monotonic() < end:
if predicate():
return True
page.wait_for_timeout(100)
return bool(predicate())
def frame_of(page, origin, path=None):
"""The frame of ``page`` whose url starts with ``origin`` (and ``path``), or None."""
prefix = origin + (path or "")
for frame in page.frames:
if frame.url.startswith(prefix):
return frame
return None
def wait_frame(page, origin, path=None, seconds=10.0):
wait_for(page, lambda: frame_of(page, origin, path) is not None, seconds)
frame = frame_of(page, origin, path)
assert frame is not None, "no frame at %s%s; page.frames = %r" % (origin, path or "", [f.url for f in page.frames])
return frame
def launch(binary, humanize=False, **kwargs):
"""The browser of every test here: seed 42, headless, no humanizing unless asked."""
from invisible_playwright import InvisiblePlaywright
return InvisiblePlaywright(seed=42, binary_path=binary, humanize=humanize, headless=True, **kwargs)
def new_page(browser, **context_kwargs):
context = browser.new_context(**context_kwargs)
page = context.new_page()
page.set_default_timeout(8000)
page.set_default_navigation_timeout(30000)
return context, page
def longest_timer_gap(observer, frame, spin_ms=SPIN_MS):
"""Make ``frame`` spin for ``spin_ms`` and return the longest gap (ms) between two ticks of a 10 ms timer that
``observer`` (a frame) runs meanwhile."""
observer.evaluate("""() => {
window.__gap = 0;
let last = performance.now();
window.__tick = setInterval(() => {
const now = performance.now();
window.__gap = Math.max(window.__gap, now - last);
last = now;
}, 10);
}""")
frame.evaluate("""(ms) => { setTimeout(() => {
const end = performance.now() + ms;
while (performance.now() < end) { /* spin */ }
}, 50); }""", spin_ms)
observer.page.wait_for_timeout(spin_ms + 800)
return observer.evaluate("() => { clearInterval(window.__tick); return window.__gap; }")
def assert_other_process(observer, frame):
"""``frame`` runs in a process of its own, not the one of ``observer``: a spin in it does not stall the timer."""
gap = longest_timer_gap(observer, frame)
assert gap < OWN_PROCESS_GAP_MS, (
"the frame at %s shares the process of the observer at %s: a %d ms spin stalled the observer's timer for "
"%.0f ms" % (frame.url, observer.url, SPIN_MS, gap))
def js(value):
"""``value`` as a JavaScript literal, for a page built from a template."""
return json.dumps(value)
def decode_png(data):
"""``(width, height, pixel)`` of a PNG made by the browser (8 bits, no interlace); ``pixel(x, y)`` is the
``(r, g, b)`` tuple. Enough to ask what colour a screenshot has at a point, with no imaging library."""
assert data[:8] == bytes([137, 80, 78, 71, 13, 10, 26, 10]), "not a PNG"
pos, idat, width = 8, b"", None
while pos < len(data):
(length,) = struct.unpack(">I", data[pos:pos + 4])
kind, body = data[pos + 4:pos + 8], data[pos + 8:pos + 8 + length]
if kind == b"IHDR":
width, height, depth, color, _, _, interlace = struct.unpack(">IIBBBBB", body)
assert depth == 8 and interlace == 0 and color in (2, 6), (depth, color, interlace)
channels = 3 if color == 2 else 4
elif kind == b"IDAT":
idat += body
pos += 12 + length
raw = zlib.decompress(idat)
stride = width * channels
rows, previous = [], bytearray(stride)
for y in range(height):
start = y * (stride + 1)
filter_type, line = raw[start], bytearray(raw[start + 1:start + 1 + stride])
for i in range(stride):
left = line[i - channels] if i >= channels else 0
up = previous[i]
upleft = previous[i - channels] if i >= channels else 0
if filter_type == 1:
line[i] = (line[i] + left) & 255
elif filter_type == 2:
line[i] = (line[i] + up) & 255
elif filter_type == 3:
line[i] = (line[i] + (left + up) // 2) & 255
elif filter_type == 4:
estimate = left + up - upleft
pa, pb, pc = abs(estimate - left), abs(estimate - up), abs(estimate - upleft)
line[i] = (line[i] + (left if pa <= pb and pa <= pc else up if pb <= pc else upleft)) & 255
rows.append(line)
previous = line
def pixel(x, y):
offset = x * channels
return tuple(rows[y][offset:offset + 3])
return width, height, pixel
def near(color, expected, tolerance=3):
"""``color`` is ``expected`` give or take ``tolerance`` per channel."""
return all(abs(a - b) <= tolerance for a, b in zip(color, expected))
+53 -19
View File
@@ -27,18 +27,22 @@ needs an ``invisible-core`` that declares them.
Layers:
* ``unit`` - ``_BASELINE`` contains the prefs with the right values. No browser.
* ``e2e`` - launch the real binary against a LOCAL HTTP harness on
``127.0.0.1`` and verify the four protocol operations that
regressed: frame URL tracking, ``handle.content_frame()``,
``frame.evaluate()``, and ``frame_locator(...).locator(...)``
element resolution. The harness uses two ports of one host,
which is one SITE: those iframes stay in the process of the
page even at strategy 1. The iframes that leave the process
(different hosts) are held by ``test_fission_strategy1_bench.py``.
* ``e2e`` - launch the real binary against a LOCAL HTTP harness and
verify the four protocol operations that regressed: frame URL
tracking, ``handle.content_frame()``, ``frame.evaluate()``, and
``frame_locator(...).locator(...)`` element resolution. The page
is served from ``127.0.0.1`` and its iframes from ``localhost``:
two hosts are two SITES, so at strategy 1 each iframe runs in a
content process of its own. (Two ports of one host would be one
site, and those iframes would stay in the process of the page.)
``test_the_iframe_runs_in_another_process`` proves it from
inside the pages, so this file cannot fall back to the process
of the page unnoticed. The bench with its own hosts and
process counts is ``test_fission_strategy1_bench.py``.
The e2e tests run entirely offline. They never call out to a real site;
the cross-origin shape is reproduced with two local HTTP servers on
random free ports.
the cross-site shape is reproduced with two local HTTP servers on random
free ports, reached by two names of the loopback interface.
"""
from __future__ import annotations
@@ -168,12 +172,13 @@ def _serve(payload: bytes) -> tuple[ThreadingHTTPServer, int]:
@pytest.fixture
def cross_origin_harness():
"""Spin up TWO local HTTP servers on different localhost ports.
"""Spin up TWO local HTTP servers: the page on ``127.0.0.1``, the iframes on ``localhost``.
Two ports = two distinct origins under SOP (same host, different port
→ different origin). The parent page on port A embeds an iframe with
src pointing at port B. Same cross-origin browsing-context shape as
a parent-page-plus-third-party-iframe layout, fully offline.
Two hosts = two SITES (and two origins under SOP). The parent page
embeds iframes with src pointing at the other host, which at strategy 1
puts them in another content process. Same cross-site browsing-context
shape as a parent-page-plus-third-party-iframe layout, fully offline.
The servers listen on 127.0.0.1 and the child is named ``localhost``.
"""
# The CHILD goes up first, because the parent's markup has to name the
# child's port and there is no longer a way to learn that number without
@@ -186,20 +191,49 @@ def cross_origin_harness():
sb, pb = _serve(child_html)
parent_html = f"""<!doctype html><html><head><title>parent</title></head><body>
<h1>parent</h1>
<iframe id="ifr_plain" src="http://127.0.0.1:{pb}/child" width="300" height="120"></iframe>
<iframe id="ifr_sandbox" src="http://127.0.0.1:{pb}/child" width="300" height="120"
<iframe id="ifr_plain" src="http://localhost:{pb}/child" width="300" height="120"></iframe>
<iframe id="ifr_sandbox" src="http://localhost:{pb}/child" width="300" height="120"
sandbox="allow-scripts allow-same-origin"></iframe>
<iframe id="ifr_titled" src="http://127.0.0.1:{pb}/child" width="300" height="120"
<iframe id="ifr_titled" src="http://localhost:{pb}/child" width="300" height="120"
title="cross-origin titled iframe"></iframe>
</body></html>""".encode("utf-8")
sa, pa = _serve(parent_html)
try:
yield {"parent_url": f"http://127.0.0.1:{pa}/", "child_origin": f"http://127.0.0.1:{pb}"}
yield {"parent_url": f"http://127.0.0.1:{pa}/", "child_origin": f"http://localhost:{pb}"}
finally:
sa.shutdown()
sb.shutdown()
@pytest.mark.e2e
def test_the_iframe_runs_in_another_process(firefox_binary, cross_origin_harness):
"""The harness of this file really crosses a process: a spin in the iframe does not stall the page.
The iframe spins for 600 ms and the page times a 10 ms timer; the timer
stalls only when both share a content process. Without this, a harness
that went back to two ports of one host would keep every test below green
while testing a same-process iframe.
"""
from _fission_frames import assert_other_process
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False) as browser:
page = browser.new_context().new_page()
# ⛔ `load`, NOT `domcontentloaded`. The `domcontentloaded` of a page says nothing about its frames: the
# frame of another site is listed as soon as it is attached, and its url is the one of its navigation,
# which commits in the frame's own process, usually AFTER the page's domcontentloaded. Read straight after
# a `domcontentloaded` goto the url was empty in 26 reads of 30 on firefox-62 (stock Playwright Firefox,
# whose frames commit in the process of the page, had it 30 of 30). After the `load` of the page the url
# was there 30 of 30 on both, with no wait: that is what is asserted here, so a `goto` that returns
# with a cross-site frame still without its url fails this test.
page.goto(cross_origin_harness["parent_url"], wait_until="load", timeout=30_000)
page.wait_for_selector("iframe#ifr_plain", timeout=10_000)
frame = page.query_selector("iframe#ifr_plain").content_frame()
assert frame is not None and cross_origin_harness["child_origin"] in frame.url, (
f"after the load of the page the iframe of the other site has url {getattr(frame, 'url', None)!r}")
assert_other_process(page.main_frame, frame)
@pytest.mark.e2e
def test_cross_origin_iframe_url_appears_in_page_frames(firefox_binary, cross_origin_harness):
"""``page.frames`` must list the cross-origin iframe with its real URL.
@@ -0,0 +1,178 @@
"""What a frame of another site starts reaches the page, and the answer reaches back.
A page of site A holds a frame of site B, which holds a frame of site C. From inside each of those two frames a
script opens a dialog (`alert`, `confirm`, `prompt`), a link starts a download, and `window.open` or a
`target=_blank` link opens a popup. In Fission the frame's process is not the page's, and each of these crosses
back to the browser process: the dialog is raised by the frame's process and answered by the driver, the download
belongs to the frame's channel, the popup is created by the frame's window with the frame's origin as its opener.
Asserted, and the same as stock Playwright Firefox does it:
* the `dialog` event of the PAGE fires for a dialog of a frame, with its type, message and default value, and what
the handler decides is what the frame's script gets back (`confirm` true or false, `prompt` the text or null);
* `page.expect_download()` fires for a link of the frame, with the file name, the url and the bytes served;
* `page.expect_popup()` fires for `window.open` and for a `target=_blank` link of the frame; the popup is at the
url asked for and `popup.opener()` is the page whose frame opened it; its `window.opener` is there for
`window.open` and absent for a `target=_blank` link, with or without `rel=noopener` (a link to a new tab is
`noopener` by default).
The first test proves the frames are in other processes (`_fission_frames.assert_other_process`), so the file
cannot turn into a same-process suite.
"""
from __future__ import annotations
import pytest
from _fission_frames import Sites, assert_other_process, launch, new_page, wait_frame
pytestmark = pytest.mark.e2e
PAYLOAD = b"fission-frame-download\x00\x01\x02" * 50
#: The controls of a document that starts things; `%s` is the url of the popup it opens.
CONTROLS = ("<button id='open' onclick=\"window.__win = window.open(%(popup)s)\">open</button>"
"<a id='blank' href=%(popup)s target='_blank'>blank</a>"
"<a id='noopener' href=%(popup)s target='_blank' rel='noopener'>noopener</a>"
"<a id='dl' href='/file.bin' download>download</a>"
"<a id='dl-header' href='/attachment.bin'>download by header</a>")
@pytest.fixture
def sites():
with Sites() as s:
popup = "'%s'" % s.url("C", "/popup")
s.route("A", "/top", "<!doctype html><title>top</title><iframe id='b' src='%s' width='600' height='300'>"
"</iframe>" % s.url("B", "/frame"))
s.route("B", "/frame", "<!doctype html><title>frame</title>" + CONTROLS % {"popup": popup}
+ "<iframe id='c' src='%s' width='450' height='150'></iframe>" % s.url("C", "/nested"))
s.route("C", "/nested", "<!doctype html><title>nested</title>" + CONTROLS % {"popup": popup})
s.route("C", "/popup", "<!doctype html><title>popup</title><body>popup at C"
"<script>window.__opener = window.opener !== null;</script>")
for site in ("B", "C"):
s.route(site, "/file.bin", PAYLOAD, ctype="application/octet-stream")
s.route(site, "/attachment.bin", PAYLOAD, ctype="application/octet-stream",
headers=[("Content-Disposition", 'attachment; filename="by-header.bin"')])
yield s
@pytest.fixture(scope="module")
def browser(firefox_binary):
with launch(firefox_binary) as browser:
yield browser
@pytest.fixture
def page(browser):
context, page = new_page(browser)
yield page
context.close()
@pytest.fixture
def opened(page, sites):
"""The page loaded, and the frame of B and the frame of C nested in it."""
page.goto(sites.url("A", "/top"), wait_until="load")
b = wait_frame(page, sites.url("B"), "/frame")
c = wait_frame(page, sites.url("C"), "/nested")
return page, {"frame": b, "nested": c}
def test_the_frames_are_in_other_processes(opened):
page, frames = opened
assert_other_process(page.main_frame, frames["frame"])
assert_other_process(frames["frame"], frames["nested"])
# ---------------------------------------------------------------------------
# dialogs
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("target", ["frame", "nested"])
@pytest.mark.parametrize("kind,accept,text,expected", [
("alert", True, None, "returned"),
("confirm", True, None, True),
("confirm", False, None, False),
("prompt", True, "typed answer", "typed answer"),
("prompt", False, None, None),
])
def test_a_dialog_of_a_frame_reaches_the_page_and_the_answer_goes_back(opened, target, kind, accept, text,
expected):
page, frames = opened
frame = frames[target]
seen = []
def on_dialog(dialog):
seen.append((dialog.type, dialog.message, dialog.default_value))
if accept:
dialog.accept(text) if text is not None else dialog.accept()
else:
dialog.dismiss()
page.on("dialog", on_dialog)
call = {"alert": "alert('hello from the frame'); window.__r = {v: 'returned'}",
"confirm": "window.__r = {v: confirm('sure?')}",
"prompt": "window.__r = {v: prompt('name?', 'default text')}"}[kind]
frame.evaluate("() => { window.__r = null; setTimeout(() => { %s }, 0); }" % call)
frame.wait_for_function("window.__r !== null")
assert frame.evaluate("window.__r.v") == expected
message, default = {"alert": ("hello from the frame", ""), "confirm": ("sure?", ""),
"prompt": ("name?", "default text")}[kind]
assert seen == [(kind, message, default)]
def test_two_dialogs_one_after_the_other_from_different_frames(opened):
"""The dialog of the nested frame, then the one of its parent: each answered in turn by the same handler."""
page, frames = opened
answers = iter([True, False])
page.on("dialog", lambda dialog: dialog.accept() if next(answers) else dialog.dismiss())
nested, frame = frames["nested"], frames["frame"]
nested.evaluate("() => { window.__r = null; setTimeout(() => { window.__r = confirm('one'); }, 0); }")
nested.wait_for_function("window.__r !== null")
frame.evaluate("() => { window.__r = null; setTimeout(() => { window.__r = confirm('two'); }, 0); }")
frame.wait_for_function("window.__r !== null")
assert nested.evaluate("window.__r") is True
assert frame.evaluate("window.__r") is False
# ---------------------------------------------------------------------------
# downloads
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("target", ["frame", "nested"])
@pytest.mark.parametrize("link,filename", [("#dl", "file.bin"), ("#dl-header", "by-header.bin")])
def test_a_download_started_in_a_frame_reaches_expect_download(opened, sites, target, link, filename):
page, frames = opened
frame = frames[target]
site, base = ("B", "/frame") if target == "frame" else ("C", "/nested")
with page.expect_download() as info:
frame.locator(link).click()
download = info.value
assert download.suggested_filename == filename
assert download.url.startswith(sites.url(site) + "/")
assert download.failure() is None
with open(download.path(), "rb") as saved:
assert saved.read() == PAYLOAD
assert frame.url == sites.url(site, base), "the frame stayed where it was"
# ---------------------------------------------------------------------------
# popups
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("target", ["frame", "nested"])
@pytest.mark.parametrize("opener_control,has_opener", [("#open", True), ("#blank", False), ("#noopener", False)])
def test_a_popup_opened_from_a_frame_reaches_expect_popup(opened, sites, target, opener_control, has_opener):
page, frames = opened
with page.expect_popup() as info:
frames[target].locator(opener_control).click()
popup = info.value
popup.wait_for_load_state("load")
assert popup.url == sites.url("C", "/popup")
assert popup.evaluate("document.title") == "popup"
assert popup.evaluate("window.__opener") is has_opener
assert popup.opener() == page, "the popup's opener is the page whose frame opened it, noopener or not"
assert popup in page.context.pages
popup.close()
@@ -0,0 +1,190 @@
"""History across a frame of another site, and the processes a context leaves behind.
Three sites (see `_fission_frames.py`): the top is A (`127.0.0.1`), the frame B (`localhost`), the frame C
(`127.0.0.2`). With Fission each site is a content process of its own, and a navigation of the frame to another
site changes its process.
* History. The page holds a frame of B. A navigation inside the frame adds a session-history entry, so
`page.go_back()` moves the FRAME back (the top url does not change, the frame is at the url it had) and
`go_forward()` restores it; the same when the frame went to a third site (a new process). A top-level
navigation and `go_back()` restore the page with its frame of another site, and the frame answers `evaluate`.
The outcome asserted is what stock Firefox does (see the docstrings).
* Processes. A context whose page had frames of other sites leaves no content process behind once it is closed:
the count of web content processes under the engine, read after each of several such contexts, does not grow.
The first test proves the frame is in another process, so the file cannot turn into a same-process suite.
"""
from __future__ import annotations
import os
import time
from pathlib import Path
import pytest
from _fission_frames import Sites, assert_other_process, launch, new_page, wait_for, wait_frame
pytestmark = pytest.mark.e2e
@pytest.fixture
def sites():
with Sites() as s:
s.route("A", "/h-top", "<!doctype html><title>h-top</title><iframe id='b' name='b' src='%s' width='500' "
"height='200'></iframe>" % s.url("B", "/h1"))
for n in (1, 2):
s.route("B", "/h%d" % n, "<!doctype html><title>h%d</title><p id='p'>h%d" % (n, n))
s.route("C", "/h3", "<!doctype html><title>h3</title><p id='p'>h3")
s.route("A", "/other", "<!doctype html><title>other</title><p>other")
yield s
@pytest.fixture
def browser(firefox_binary):
with launch(firefox_binary) as browser:
yield browser
@pytest.fixture
def page(browser):
context, page = new_page(browser)
yield page
context.close()
def traverse(page, direction):
"""``page.go_back()`` or ``page.go_forward()``. When the entry belongs to a frame, no navigation of the main
frame follows, and the call gives up with a ``TimeoutError`` after the history has moved: as stock Firefox
does. A call that returns is just as good; what the tests judge is where the page and its frame are after."""
try:
getattr(page, direction)(timeout=3000)
except Exception as error: # the client's own TimeoutError class: the wrapper ships its own copy
if type(error).__name__ != "TimeoutError":
raise
def _frame_url(page):
"""The url of the one frame of the page, once there is one."""
wait_for(page, lambda: len(page.frames) == 2)
return page.frames[1].url
def test_the_frame_is_in_another_process(page, sites):
page.goto(sites.url("A", "/h-top"), wait_until="load")
assert_other_process(page.main_frame, wait_frame(page, sites.url("B"), "/h1"))
def test_back_and_forward_move_the_frame_not_the_top_after_a_navigation_inside_it(page, sites):
"""The frame goes h1 -> h2 (same site). Back: the top is where it was, the frame is at h1. Forward: at h2."""
page.goto(sites.url("A", "/h-top"), wait_until="load")
frame = wait_frame(page, sites.url("B"), "/h1")
frame.goto(sites.url("B", "/h2"))
assert frame.url == sites.url("B", "/h2") and page.url == sites.url("A", "/h-top")
traverse(page, "go_back")
assert wait_for(page, lambda: _frame_url(page) == sites.url("B", "/h1")), _frame_url(page)
assert page.url == sites.url("A", "/h-top")
assert page.frames[1].evaluate("document.title") == "h1"
traverse(page, "go_forward")
assert wait_for(page, lambda: _frame_url(page) == sites.url("B", "/h2")), _frame_url(page)
assert page.url == sites.url("A", "/h-top")
assert page.frames[1].evaluate("document.title") == "h2"
def test_back_and_forward_across_a_frame_that_went_to_a_third_site(page, sites):
"""The frame goes h1 (B) -> h2 (B) -> h3 (C: a change of site and of process). Each back moves it one entry; forward goes the way back came."""
page.goto(sites.url("A", "/h-top"), wait_until="load")
frame = wait_frame(page, sites.url("B"), "/h1")
frame.goto(sites.url("B", "/h2"))
frame.goto(sites.url("C", "/h3"))
assert wait_for(page, lambda: _frame_url(page) == sites.url("C", "/h3")), _frame_url(page)
assert_other_process(page.main_frame, page.frames[1])
for expected in ("B/h2", "B/h1"):
traverse(page, "go_back")
site, path = expected.split("/")
assert wait_for(page, lambda: _frame_url(page) == sites.url(site, "/" + path)), (expected, _frame_url(page))
assert page.url == sites.url("A", "/h-top")
assert page.frames[1].evaluate("document.title") == path
traverse(page, "go_forward")
assert wait_for(page, lambda: _frame_url(page) == sites.url("B", "/h2")), _frame_url(page)
traverse(page, "go_forward")
assert wait_for(page, lambda: _frame_url(page) == sites.url("C", "/h3")), _frame_url(page)
assert page.frames[1].evaluate("document.title") == "h3"
assert page.url == sites.url("A", "/h-top")
def test_a_top_level_navigation_and_back_restore_the_page_with_its_frame_usable(page, sites):
page.goto(sites.url("A", "/h-top"), wait_until="load")
frame = wait_frame(page, sites.url("B"), "/h1")
frame.goto(sites.url("B", "/h2"))
page.goto(sites.url("A", "/other"), wait_until="load")
assert page.url == sites.url("A", "/other")
traverse(page, "go_back")
assert page.url == sites.url("A", "/h-top")
assert wait_for(page, lambda: len(page.frames) == 2 and page.frames[1].url.startswith(sites.url("B"))), \
[f.url for f in page.frames]
restored = page.frames[1]
# the frame is where it was when the page was left (h2), as stock Firefox restores it
assert restored.url == sites.url("B", "/h2")
assert restored.evaluate("document.title") == "h2"
assert restored.evaluate("location.origin") == sites.url("B")
assert restored.locator("#p").inner_text() == "h2"
assert_other_process(page.main_frame, restored)
# ---------------------------------------------------------------------------
# processes
# ---------------------------------------------------------------------------
def _content_processes(engine_dir):
"""The pids of the engine's web content processes (`-contentproc ... tab`) below this test."""
import psutil
found = set()
for child in psutil.Process(os.getpid()).children(recursive=True):
try:
if not os.path.normcase(child.exe()).startswith(os.path.normcase(engine_dir)):
continue
command = child.cmdline()
except psutil.Error:
continue
if "-contentproc" in command and command[-1] == "tab":
found.add(child.pid)
return found
def _settled(engine_dir, seconds=2.0, limit=25.0):
"""The set of content processes once it has not changed for ``seconds``."""
end = time.monotonic() + limit
last, since = _content_processes(engine_dir), time.monotonic()
while time.monotonic() < end:
time.sleep(0.25)
now = _content_processes(engine_dir)
if now != last:
last, since = now, time.monotonic()
elif time.monotonic() - since >= seconds:
break
return last
def test_a_closed_context_with_frames_of_other_sites_leaves_no_content_process(firefox_binary, sites):
"""Four contexts in a row, each with a page whose frames are on B and (nested) on C. The processes the frames
took are gone once the context is closed: the count after the last is no higher than the count after the
first (the engine keeps one spare process that the first context may take or leave)."""
sites.route("B", "/leak-b", "<!doctype html><title>b</title><iframe src='%s'></iframe>" % sites.url("C", "/h3"))
sites.route("A", "/leak", "<!doctype html><title>leak</title><iframe id='b' src='%s'></iframe>"
% sites.url("B", "/leak-b"))
engine_dir = str(Path(firefox_binary).resolve().parent)
with launch(firefox_binary) as browser:
counts, during = [], []
for _ in range(4):
context, page = new_page(browser)
page.goto(sites.url("A", "/leak"), wait_until="load")
wait_frame(page, sites.url("C"), "/h3")
during.append(len(_settled(engine_dir)))
context.close()
counts.append(len(_settled(engine_dir)))
assert max(during) > counts[0], (
"the frames of other sites took no process of their own: %r while open, %r after" % (during, counts))
assert counts[-1] <= counts[0], "web content processes after each closed context: %r (open: %r)" % (
counts, during)
@@ -0,0 +1,351 @@
"""Routes, exposed functions, init scripts and postMessage, for an iframe of another site and one nested in it.
Fission puts a frame of another site in a content process of its own. What a script written against the Playwright
API does with such a frame is the same as with any other, and this file holds the parts that go through the
frame's own process:
* `page.route` and `context.route` see the requests the frame makes, `request.frame` is that frame (the same
object `page.frames` lists, with the url of its document), and fulfill, abort and continue each take effect in the
frame; `wait_for_load_state("networkidle")` waits for the late requests of the frame;
* `expose_function` and `expose_binding` are callable from the frame and from a frame nested in it, and the
binding's `source["frame"]` is the frame that called;
* an init script runs before the frame's own scripts, in the frame, in the nested frame, and again in the document
the frame navigates to (a third site);
* `postMessage` crosses between the top and a frame of another site both ways, and between two sibling frames of
other sites through the top: `event.origin` is the sender's, `event.source` answers.
The sites are told apart by host (see `_fission_frames.py`): the top is A (`127.0.0.1`), the frame is B
(`localhost`) and the frame nested in it is C (`127.0.0.2`).
The outcome asserted is the one of stock Playwright Firefox; none of it depends on the process model, and the
first test proves the frame is not in the process of the page, so the file cannot turn into a same-process suite.
"""
from __future__ import annotations
import json
import pytest
from _fission_frames import Sites, assert_other_process, launch, new_page, wait_frame
pytestmark = pytest.mark.e2e
@pytest.fixture
def sites():
with Sites() as s:
# A top page with a frame of B; the frame of B holds a frame of C. Each document reports through
# window.__log what it did, so a test reads it with evaluate.
s.route("A", "/top", '<!doctype html><title>top</title><iframe id="b" name="b" src="%s" '
'width="500" height="300"></iframe>' % s.url("B", "/frame"))
s.route("B", "/frame", '<!doctype html><title>frame</title><iframe id="c" name="c" src="%s" '
'width="300" height="150"></iframe>'
"<script>window.__got = [];"
"fetch('/api/b?from=load').then(r => r.text()).then(t => __got.push(['load', t]))"
".catch(e => __got.push(['load-error', String(e)]));</script>" % s.url("C", "/nested"))
s.route("C", "/nested", "<!doctype html><title>nested</title>"
"<script>window.__got = [];"
"fetch('/api/c?from=load').then(r => r.text()).then(t => __got.push(['load', t]))"
".catch(e => __got.push(['load-error', String(e)]));</script>")
s.route("B", "/api/b", "from-server-b", ctype="text/plain")
s.route("C", "/api/c", "from-server-c", ctype="text/plain")
yield s
@pytest.fixture(scope="module")
def browser(firefox_binary):
with launch(firefox_binary) as browser:
yield browser
@pytest.fixture
def page(browser):
context, page = new_page(browser)
yield page
context.close()
def _frames(page, sites):
"""The frame of B and the frame of C nested in it, once both have a document."""
b = wait_frame(page, sites.url("B"), "/frame")
c = wait_frame(page, sites.url("C"), "/nested")
return b, c
def test_the_frame_is_in_another_process_and_the_nested_one_in_a_third(page, sites):
"""The precondition of this file: B is not in the process of A, and C is not in the one of B."""
page.goto(sites.url("A", "/top"), wait_until="load")
b, c = _frames(page, sites)
assert b.parent_frame == page.main_frame and c.parent_frame == b
assert_other_process(page.main_frame, b)
assert_other_process(b, c)
# ---------------------------------------------------------------------------
# page.route and context.route
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("where", ["page", "context"])
def test_a_route_sees_the_requests_of_a_frame_of_another_site_and_of_a_nested_one(page, sites, where):
"""The handler is called for the fetch of the frame of B and the one of the frame of C nested in it,
`request.frame` is the frame that made it (the object of `page.frames`, with its url), the request is a
sub-resource of that frame's document, and continuing it gives the page the server's answer."""
context = page.context
seen = []
def handler(route):
request = route.request
seen.append((request.url, request.frame, request.resource_type))
route.continue_()
(page if where == "page" else context).route("**/api/**", handler)
page.goto(sites.url("A", "/top"), wait_until="load")
b, c = _frames(page, sites)
for frame in (b, c):
frame.wait_for_function("window.__got.length > 0")
assert b.evaluate("window.__got") == [["load", "from-server-b"]]
assert c.evaluate("window.__got") == [["load", "from-server-c"]]
by_url = {url.split("?")[0]: (frame, kind) for url, frame, kind in seen}
assert set(by_url) == {sites.url("B", "/api/b"), sites.url("C", "/api/c")}, seen
frame_of_b, kind_b = by_url[sites.url("B", "/api/b")]
frame_of_c, kind_c = by_url[sites.url("C", "/api/c")]
assert frame_of_b is b and frame_of_b.url == sites.url("B", "/frame")
assert frame_of_c is c and frame_of_c.url == sites.url("C", "/nested")
assert frame_of_c.parent_frame is b
assert kind_b == kind_c == "fetch"
@pytest.mark.parametrize("action", ["fulfill", "abort", "continue"])
@pytest.mark.parametrize("target", ["frame", "nested"])
def test_fulfill_abort_and_continue_take_effect_in_a_frame_of_another_site(page, sites, action, target):
"""What the route decides is what the frame's fetch gets: the body and status given to `fulfill`, a rejected
fetch for `abort`, the server's answer for `continue`. A fetch the frame makes AFTER the load, to a url the
route covers."""
page.goto(sites.url("A", "/top"), wait_until="load")
b, c = _frames(page, sites)
frame, site = (b, "B") if target == "frame" else (c, "C")
sites.route(site, "/api/late", "from-server", ctype="text/plain")
routed = []
def handler(route):
routed.append(route.request.frame)
if action == "fulfill":
route.fulfill(status=201, body="from-route", content_type="text/plain",
headers={"access-control-allow-origin": "*"})
elif action == "abort":
route.abort()
else:
route.continue_()
page.route("**/api/late", handler)
result = frame.evaluate("""() => fetch('/api/late').then(
r => r.text().then(t => ({ok: true, status: r.status, body: t})),
e => ({ok: false, error: e.name}))""")
assert routed == [frame], routed
if action == "fulfill":
assert result == {"ok": True, "status": 201, "body": "from-route"}
elif action == "abort":
assert result["ok"] is False and result["error"] == "TypeError", result
assert not sites.seen(site, "/api/late"), "an aborted request reached the server"
else:
assert result == {"ok": True, "status": 200, "body": "from-server"}
assert len(sites.seen(site, "/api/late")) == 1
def test_a_route_set_before_the_load_fulfills_what_the_frame_asks_while_loading(page, sites):
"""The first request of the frame of another site is covered: the route is in place before the page goes to
its url, and the fetch the frame makes while loading is answered by the route."""
page.route("**/api/b**", lambda route: route.fulfill(body="routed-b", content_type="text/plain"))
page.goto(sites.url("A", "/top"), wait_until="load")
b, _ = _frames(page, sites)
b.wait_for_function("window.__got.length > 0")
assert b.evaluate("window.__got") == [["load", "routed-b"]]
assert not sites.seen("B", "/api/b"), "the request reached the server through the route"
def test_networkidle_waits_for_the_late_requests_of_a_frame_of_another_site(page, sites):
"""The frame makes a request 200 ms after it loads, and the next one as soon as that answers (the server holds
each for 300 ms): there is never half a second without a request, so `networkidle` of the PAGE is not reached
before both are done."""
chain = ("<!doctype html><title>late</title><script>window.__done = [];"
"addEventListener('load', () => setTimeout(() => fetch('/late/1').then(r => r.text())"
".then(t => { __done.push(t); return fetch('/late/2'); }).then(r => r.text())"
".then(t => __done.push(t)), 200));</script>")
sites.route("B", "/late-frame", chain)
sites.route("B", "/late/1", "one", ctype="text/plain", delay=0.3)
sites.route("B", "/late/2", "two", ctype="text/plain", delay=0.3)
sites.route("A", "/late-top", '<!doctype html><title>late top</title>'
'<iframe src="%s" width="300" height="100"></iframe>' % sites.url("B", "/late-frame"))
page.goto(sites.url("A", "/late-top"), wait_until="networkidle", timeout=30000)
frame = wait_frame(page, sites.url("B"), "/late-frame")
assert frame.evaluate("window.__done") == ["one", "two"]
page.wait_for_load_state("networkidle")
# ---------------------------------------------------------------------------
# expose_function, expose_binding and init scripts
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("where", ["page", "context"])
def test_an_exposed_function_is_callable_from_a_frame_of_another_site_and_a_nested_one(page, sites, where):
context = page.context
(page if where == "page" else context).expose_function("add", lambda a, b: a + b)
page.goto(sites.url("A", "/top"), wait_until="load")
b, c = _frames(page, sites)
assert b.evaluate("add(2, 3)") == 5
assert c.evaluate("add(40, 2)") == 42
assert c.evaluate("typeof window.add") == "function"
@pytest.mark.parametrize("where", ["page", "context"])
def test_a_binding_knows_which_frame_called_it(page, sites, where):
"""`source["frame"]` is the frame that called: the frame of B, then the frame of C nested in it, then the
top; `source["page"]` is the page."""
context = page.context
calls = []
def binding(source, value):
calls.append((source["frame"], source["page"], value))
return "ack:%s" % value
(page if where == "page" else context).expose_binding("report", binding)
page.goto(sites.url("A", "/top"), wait_until="load")
b, c = _frames(page, sites)
assert c.evaluate("report('from-c')") == "ack:from-c"
assert b.evaluate("report('from-b')") == "ack:from-b"
assert page.main_frame.evaluate("report('from-top')") == "ack:from-top"
assert [(f, p is page, v) for f, p, v in calls] == [(c, True, "from-c"), (b, True, "from-b"),
(page.main_frame, True, "from-top")]
assert calls[0][0].url == sites.url("C", "/nested")
assert calls[1][0].url == sites.url("B", "/frame")
def test_a_binding_called_by_a_script_of_the_frame_while_it_loads(page, sites):
"""A page script of the frame of B calls the binding in its own first script, before any `evaluate`: the
binding is already there and knows the frame."""
sites.route("B", "/binds", "<!doctype html><title>binds</title><script>window.__ack = null;"
"report('while-loading').then(v => window.__ack = v);</script>")
sites.route("A", "/binds-top", '<!doctype html><iframe src="%s"></iframe>' % sites.url("B", "/binds"))
calls = []
def binding(source, value):
calls.append((source["frame"].url, value))
return "ack"
page.expose_binding("report", binding)
page.goto(sites.url("A", "/binds-top"), wait_until="load")
frame = wait_frame(page, sites.url("B"), "/binds")
frame.wait_for_function("window.__ack !== null")
assert calls == [(sites.url("B", "/binds"), "while-loading")]
ORDER_PAGE = ("<!doctype html><title>%s</title><script>"
"window.__seen = JSON.stringify(window.__o || []);"
"(window.__o = window.__o || []).push('page');</script>")
@pytest.mark.parametrize("where", ["page", "context"])
def test_an_init_script_runs_before_the_scripts_of_a_frame_of_another_site(page, sites, where):
"""In the top, in the frame of B and in the frame of C: the init script has pushed 'init' before the
document's own first script reads the list. The same, again, in the document the frame of B navigates to on a
third site (C): the new document in the new process gets the script before its own."""
context = page.context
script = "(window.__o = window.__o || []).push('init');"
(page if where == "page" else context).add_init_script(script)
sites.route("A", "/order-top", ORDER_PAGE.replace("%s", "top")
+ '<iframe src="%s"></iframe>' % sites.url("B", "/order-b"))
sites.route("B", "/order-b", ORDER_PAGE.replace("%s", "b")
+ '<iframe src="%s"></iframe>' % sites.url("C", "/order-c"))
sites.route("C", "/order-c", ORDER_PAGE.replace("%s", "c"))
sites.route("C", "/order-moved", ORDER_PAGE.replace("%s", "moved"))
page.goto(sites.url("A", "/order-top"), wait_until="load")
b = wait_frame(page, sites.url("B"), "/order-b")
c = wait_frame(page, sites.url("C"), "/order-c")
for frame in (page.main_frame, b, c):
assert frame.evaluate("window.__seen") == '["init"]', frame.url
assert frame.evaluate("window.__o") == ["init", "page"], frame.url
b.goto(sites.url("C", "/order-moved"))
assert b.url == sites.url("C", "/order-moved")
assert b.evaluate("window.__seen") == '["init"]'
assert b.evaluate("window.__o") == ["init", "page"]
# and the process changed with the site: the moved frame is not in the top's process either
assert_other_process(page.main_frame, b)
# ---------------------------------------------------------------------------
# postMessage
# ---------------------------------------------------------------------------
ECHO = ("<!doctype html><title>%(name)s</title><script>window.__in = [];"
"addEventListener('message', e => { __in.push({origin: e.origin, data: e.data, "
"fromParent: e.source === parent});"
"if (e.data && e.data.ping) e.source.postMessage({pong: e.data.ping, by: %(name)s}, e.origin); });"
"</script>")
def test_post_message_crosses_between_the_top_and_a_frame_of_another_site_both_ways(page, sites):
"""The top asks the frame of B, the frame answers on `event.source`, the top reads the answer with the origin
of B and `event.source` equal to the frame's window; and the frame speaks first to its parent."""
sites.route("B", "/echo", ECHO % {"name": '"b"'} +
"<script>parent.postMessage({hello: 'from-b'}, '*');</script>")
sites.route("A", "/msg-top", "<!doctype html><title>top</title><iframe id='f' src='%s'></iframe><script>"
"window.__in = []; addEventListener('message', e => __in.push({origin: e.origin, data: e.data, "
"fromFrame: e.source === document.getElementById('f').contentWindow}));</script>"
% sites.url("B", "/echo"))
page.goto(sites.url("A", "/msg-top"), wait_until="load")
frame = wait_frame(page, sites.url("B"), "/echo")
page.wait_for_function("window.__in.length >= 1")
assert page.evaluate("window.__in[0]") == {"origin": sites.url("B"), "data": {"hello": "from-b"},
"fromFrame": True}
page.evaluate("document.getElementById('f').contentWindow.postMessage({ping: 7}, %s)" % json.dumps(sites.url("B")))
page.wait_for_function("window.__in.length >= 2")
assert page.evaluate("window.__in[1]") == {"origin": sites.url("B"), "data": {"pong": 7, "by": "b"},
"fromFrame": True}
assert frame.evaluate("window.__in") == [{"origin": sites.url("A"), "data": {"ping": 7}, "fromParent": True}]
def test_post_message_between_two_sibling_frames_of_other_sites_goes_through_the_top(page, sites):
"""Frames of B and C side by side, in a page of A. They cannot see each other, only the top: B writes to the
top, the top relays to C naming the sender, C answers the top on `event.source`, the top relays back. Every
hop shows the origin of the document that sent it."""
sites.route("B", "/left", "<!doctype html><title>left</title><script>window.__in = [];"
"addEventListener('message', e => __in.push({origin: e.origin, data: e.data}));"
"parent.postMessage({to: 'right', text: 'hi from left'}, '*');</script>")
sites.route("C", "/right", "<!doctype html><title>right</title><script>window.__in = [];"
"addEventListener('message', e => { __in.push({origin: e.origin, data: e.data});"
"e.source.postMessage({to: 'left', text: 'hi from right'}, e.origin); });</script>")
# The top relays a message only once the frame it is for has loaded: the two frames load in two processes, in no
# fixed order, and a message posted to a frame whose document is not there yet is lost in any browser. The first
# version relayed at once, and one CI run in three never saw the answer.
sites.route("A", "/relay", "<!doctype html><title>relay</title><script>"
"window.__hops = []; window.__loaded = {}; window.__waiting = [];"
"const win = id => document.getElementById(id).contentWindow;"
"function deliver() { __waiting = __waiting.filter(m => {"
" if (!__loaded[m.to]) return true; win(m.to).postMessage(m.message, m.origin); return false; }); }"
"function loaded(id) { __loaded[id] = true; deliver(); }"
"addEventListener('message', e => {"
" const from = e.source === win('left') ? 'left' : e.source === win('right') ? 'right' : '?';"
" __hops.push({from, origin: e.origin, data: e.data});"
" if (e.data.to) { __waiting.push({to: e.data.to, message: {relayed: e.data.text, by: from},"
" origin: from === 'left' ? %s : %s}); deliver(); }"
"});</script>"
"<iframe id='left' onload=\"loaded('left')\" src='%s'></iframe>"
"<iframe id='right' onload=\"loaded('right')\" src='%s'></iframe>"
% (json.dumps(sites.url("C")), json.dumps(sites.url("B")),
sites.url("B", "/left"), sites.url("C", "/right")))
page.goto(sites.url("A", "/relay"), wait_until="load")
left = wait_frame(page, sites.url("B"), "/left")
right = wait_frame(page, sites.url("C"), "/right")
page.wait_for_function("window.__hops.length >= 2")
left.wait_for_function("window.__in.length >= 1")
assert page.evaluate("window.__hops") == [
{"from": "left", "origin": sites.url("B"), "data": {"to": "right", "text": "hi from left"}},
{"from": "right", "origin": sites.url("C"), "data": {"to": "left", "text": "hi from right"}},
]
assert right.evaluate("window.__in") == [
{"origin": sites.url("A"), "data": {"relayed": "hi from left", "by": "left"}}]
assert left.evaluate("window.__in") == [
{"origin": sites.url("A"), "data": {"relayed": "hi from right", "by": "right"}}]
assert_other_process(left, right)
@@ -0,0 +1,371 @@
"""The frame tree, typing, trusted clicks and screenshots, with frames in other processes.
Three sites (see `_fission_frames.py`): the top is A (`127.0.0.1`), the frame B (`localhost`), the frame C
(`127.0.0.2`). With Fission each site is a content process of its own, and the page the script drives is made of
documents that live in different ones. What a script written against the Playwright API does with such a page is
what it does with any other:
* the frame tree A > B > A > C (the second A is the site of the top again, below a frame of another site): every
level is in `page.frames` with its url and name, and `parent_frame` / `child_frames` give the same chain;
* typing into an input of a frame of another site and of a frame nested in it (`press_sequentially`,
`keyboard.type` after a focus, `press`): the keys are trusted and reach that input; `wait_for_selector` and
`Locator.wait_for` see an element that appears there later;
* a click by selector on an element inside such a frame lands on THAT element when the iframe is under a CSS
transform (scale and translate) and after the top page and the frame have both been scrolled (the page
records which element got the trusted click);
* `page.screenshot()` of a page whose frame of another site paints a known colour shows that colour inside the
frame's box, and `locator.screenshot()` of an element inside the frame, and inside a nested one, has the
element's size and colour.
Every test with a frame of B is run for the frame nested in it (C) as well where the scenario has one. The first
test of the file proves the frames are in other processes, so it cannot turn into a same-process suite.
"""
from __future__ import annotations
import pytest
from _fission_frames import (Sites, assert_other_process, decode_png, launch, near, new_page, wait_for,
wait_frame)
pytestmark = pytest.mark.e2e
@pytest.fixture
def sites():
with Sites() as s:
yield s
@pytest.fixture
def browser(firefox_binary):
with launch(firefox_binary) as browser:
yield browser
@pytest.fixture
def page(browser):
context, page = new_page(browser)
yield page
context.close()
# ---------------------------------------------------------------------------
# 1. the frame tree A > B > A > C
# ---------------------------------------------------------------------------
@pytest.fixture
def tree(sites):
sites.route("A", "/tree", "<!doctype html><title>level 0</title><iframe id='one' name='one' src='%s' "
"width='700' height='500'></iframe>" % sites.url("B", "/level1"))
sites.route("B", "/level1", "<!doctype html><title>level 1</title><iframe id='two' name='two' src='%s' "
"width='600' height='400'></iframe>" % sites.url("A", "/level2"))
sites.route("A", "/level2", "<!doctype html><title>level 2</title><iframe id='three' name='three' src='%s' "
"width='500' height='300'></iframe>" % sites.url("C", "/level3"))
sites.route("C", "/level3", "<!doctype html><title>level 3</title><p id='leaf'>leaf of the tree")
return sites
def test_the_tree_a_b_a_c_is_listed_at_every_level(page, tree):
page.goto(tree.url("A", "/tree"), wait_until="load")
wait_frame(page, tree.url("C"), "/level3")
expected = [("", tree.url("A", "/tree")), ("one", tree.url("B", "/level1")),
("two", tree.url("A", "/level2")), ("three", tree.url("C", "/level3"))]
assert wait_for(page, lambda: [(f.name, f.url) for f in page.frames] == expected), \
[(f.name, f.url) for f in page.frames]
main, one, two, three = page.frames
assert main == page.main_frame
assert [f.parent_frame for f in (main, one, two, three)] == [None, main, one, two]
assert [f.child_frames for f in (main, one, two, three)] == [[one], [two], [three], []]
assert all(f.page is page for f in page.frames)
assert [f.is_detached() for f in page.frames] == [False] * 4
# the lookups by name and by url find the same objects
assert page.frame(name="three") is three and page.frame(url=tree.url("A", "/level2")) is two
# and the document of each level answers for itself
assert [f.evaluate("location.href") for f in page.frames] == [u for _, u in expected]
assert [f.evaluate("document.title") for f in page.frames] == ["level 0", "level 1", "level 2", "level 3"]
assert [f.evaluate("window.name") for f in page.frames] == ["", "one", "two", "three"]
assert three.locator("#leaf").inner_text() == "leaf of the tree"
# the frames are in other processes: B is not A, and C is neither B nor the second A
assert_other_process(main, one)
assert_other_process(two, three)
# ---------------------------------------------------------------------------
# 2. typing, and waiting for what appears later
# ---------------------------------------------------------------------------
TYPING = ("<input id='t' autocomplete='off'><script>window.keys = [];"
"t.addEventListener('keydown', e => keys.push([e.key, e.isTrusted]));</script>")
@pytest.fixture
def typing(sites):
sites.route("A", "/typing", "<!doctype html><title>top</title><iframe id='b' src='%s' width='600' height='400'>"
"</iframe>" % sites.url("B", "/typing-b"))
sites.route("B", "/typing-b", "<!doctype html><title>b</title>" + TYPING +
"<iframe id='c' src='%s' width='400' height='150'></iframe>" % sites.url("C", "/typing-c"))
sites.route("C", "/typing-c", "<!doctype html><title>c</title>" + TYPING)
return sites
def _typing_frames(page, typing):
page.goto(typing.url("A", "/typing"), wait_until="load")
return {"frame": wait_frame(page, typing.url("B"), "/typing-b"),
"nested": wait_frame(page, typing.url("C"), "/typing-c")}
@pytest.mark.parametrize("target", ["frame", "nested"])
@pytest.mark.parametrize("how", ["press_sequentially", "keyboard_type", "press_keys"])
def test_typing_into_an_input_of_a_frame_of_another_site(page, typing, target, how):
frame = _typing_frames(page, typing)[target]
field = frame.locator("#t")
if how == "press_sequentially":
field.press_sequentially("Hello 42")
expected, keys = "Hello 42", list("Hello 42")
elif how == "keyboard_type":
field.focus()
assert frame.evaluate("document.activeElement.id") == "t"
page.keyboard.type("Typed text")
expected, keys = "Typed text", list("Typed text")
else:
field.focus()
for key in ("a", "b", "c", "Backspace", "d"):
page.keyboard.press(key)
field.press("e")
expected, keys = "abde", ["a", "b", "c", "Backspace", "d", "e"]
assert field.input_value() == expected
seen = frame.evaluate("window.keys")
# a capital letter is typed with the Shift key held, as on a keyboard: its own keydown comes first
assert [k for k, _ in seen if k != "Shift"] == keys
assert all(trusted for _, trusted in seen), seen
def test_the_other_frames_are_not_typed_into(page, typing):
"""The keys go to the focused input and to no other document: the input of the nested frame and the one of
its parent each keep only what was typed in them."""
frames = _typing_frames(page, typing)
frames["frame"].locator("#t").press_sequentially("outer")
frames["nested"].locator("#t").press_sequentially("inner")
assert frames["frame"].locator("#t").input_value() == "outer"
assert frames["nested"].locator("#t").input_value() == "inner"
assert [k for k, _ in frames["frame"].evaluate("window.keys")] == list("outer")
assert [k for k, _ in frames["nested"].evaluate("window.keys")] == list("inner")
LATE = ("<p id='anchor'>anchor</p><script>"
"setTimeout(() => { const d = document.createElement('div'); d.id = 'late'; d.textContent = 'arrived';"
"document.body.appendChild(d); }, 700);"
"setTimeout(() => { const d = document.createElement('div'); d.id = 'shown'; d.textContent = 'shown';"
"d.style.display = 'none'; document.body.appendChild(d); }, 300);"
"setTimeout(() => { document.getElementById('shown').style.display = 'block'; }, 1000);</script>")
@pytest.fixture
def late(sites):
sites.route("A", "/late", "<!doctype html><title>top</title><iframe id='b' src='%s' width='600' height='400'>"
"</iframe>" % sites.url("B", "/late-b"))
sites.route("B", "/late-b", "<!doctype html><title>b</title>" + LATE +
"<iframe id='c' src='%s' width='400' height='150'></iframe>" % sites.url("C", "/late-c"))
sites.route("C", "/late-c", "<!doctype html><title>c</title>" + LATE)
return sites
@pytest.mark.parametrize("target", ["frame", "nested"])
def test_waiting_for_an_element_that_appears_later_in_a_frame_of_another_site(page, late, target):
page.goto(late.url("A", "/late"), wait_until="load")
frame = {"frame": wait_frame(page, late.url("B"), "/late-b"),
"nested": wait_frame(page, late.url("C"), "/late-c")}[target]
# the element is not there yet when the wait starts, or it is by now: either way the wait returns it
handle = frame.wait_for_selector("#late", timeout=8000)
try:
assert handle.inner_text() == "arrived"
assert handle.owner_frame() is frame
finally:
handle.dispose()
# the same, by the locator of the frame and by the frame locator of the page
frame.locator("#shown").wait_for(state="visible", timeout=8000)
outer = page.frame_locator("#b")
scoped = outer.locator("#late") if target == "frame" else outer.frame_locator("#c").locator("#late")
scoped.wait_for(state="attached", timeout=8000)
assert scoped.inner_text() == "arrived"
def test_waiting_in_a_frame_of_another_site_times_out_on_what_never_comes(page, late):
"""The wait is not satisfied by an element of another document: `#nothing` is in none, and the error is the
wait's TimeoutError naming the selector, not a protocol error about the frame."""
page.goto(late.url("A", "/late"), wait_until="load")
frame = wait_frame(page, late.url("B"), "/late-b")
with pytest.raises(Exception) as error:
frame.wait_for_selector("#nothing", timeout=1500)
assert type(error.value).__name__ == "TimeoutError" and "#nothing" in str(error.value), error.value
# ---------------------------------------------------------------------------
# 3. a click by selector under a transform and after scrolling
# ---------------------------------------------------------------------------
GRID = ("<style>html,body{margin:0}button{position:absolute;width:60px;height:40px;margin:0;padding:0}"
"%s</style>%s<script>window.landed = [];"
"addEventListener('click', e => landed.push({id: e.target.id || e.target.tagName, "
"trusted: e.isTrusted}), true);</script>")
def _grid(rows=4, cols=4, tall=0):
css = "".join("#r%dc%d{left:%dpx;top:%dpx}" % (r, c, 20 + c * 90, 20 + r * 70) for r in range(rows)
for c in range(cols))
buttons = "".join("<button id='r%dc%d'>%d,%d</button>" % (r, c, r, c) for r in range(rows)
for c in range(cols))
if tall:
buttons += "<div style='position:absolute;left:0;top:%dpx;width:10px;height:10px'></div>" % tall
return GRID % (css, buttons)
@pytest.fixture
def transformed(sites):
"""The frame of B inside a transformed box; the frame of C inside that one, transformed as well."""
sites.route("B", "/grid", "<!doctype html>" + _grid() +
"<iframe id='c' src='%s' style='position:absolute;left:400px;top:20px;width:420px;height:320px;"
"border:0;transform:translate(10px, 15px) scale(0.75);transform-origin:0 0'></iframe>"
% sites.url("C", "/grid"))
sites.route("C", "/grid", "<!doctype html>" + _grid(3, 3))
return sites
TRANSFORMS = [("scale", "translate(40px, 30px) scale(0.5)"), ("scale-up", "translate(10px, 10px) scale(1.4)"),
("rotate-ish", "translate(60px, 20px) scale(0.8) skewX(-8deg)")]
@pytest.fixture(params=[False, True], ids=["plain", "humanized"])
def pointer_browser(request, firefox_binary):
"""A browser per way of moving the pointer: a click of the humanized one lands off the centre of the element."""
with launch(firefox_binary, humanize=request.param) as browser:
yield browser
@pytest.fixture
def pointer_page(pointer_browser):
context, page = new_page(pointer_browser)
yield page
context.close()
@pytest.mark.parametrize("name,transform", TRANSFORMS, ids=[t[0] for t in TRANSFORMS])
def test_a_click_by_selector_in_a_frame_under_a_transform_lands_on_that_element(pointer_page, transformed, name,
transform):
"""The iframe sits in a box under `transform` (translate and scale, and a skew). One click per button, by
selector, in the frame of B and in the frame of C nested in it (which is transformed as well): each is
recorded by the document it landed in, as a trusted click on the button that was asked for, and by that
document only."""
page = pointer_page
transformed.route("A", "/t", "<!doctype html><title>t</title><body style='margin:0;height:2000px'>"
"<div style='transform:%s;transform-origin:0 0;position:absolute;left:30px;top:20px'>"
"<iframe id='b' src='%s' width='900' height='450' style='border:0'></iframe></div>"
% (transform, transformed.url("B", "/grid")))
page.goto(transformed.url("A", "/t"), wait_until="load")
frames = {"frame": wait_frame(page, transformed.url("B"), "/grid"),
"nested": wait_frame(page, transformed.url("C"), "/grid")}
expected = {"frame": [], "nested": []}
for target, button in (("frame", "r2c1"), ("nested", "r1c1"), ("frame", "r3c3"), ("nested", "r2c2"),
("frame", "r0c0")):
frames[target].locator("#" + button).click()
expected[target].append({"id": button, "trusted": True})
for name_, frame in frames.items():
assert frame.evaluate("window.landed") == expected[name_], (target, button, name_)
def test_the_transformed_frames_are_in_other_processes(pointer_page, transformed):
page = pointer_page
transformed.route("A", "/t", "<!doctype html><title>t</title><div style='transform:scale(0.5)'>"
"<iframe id='b' src='%s' width='900' height='450'></iframe></div>"
% transformed.url("B", "/grid"))
page.goto(transformed.url("A", "/t"), wait_until="load")
b = wait_frame(page, transformed.url("B"), "/grid")
assert_other_process(page.main_frame, b)
assert_other_process(b, wait_frame(page, transformed.url("C"), "/grid"))
def test_a_click_by_selector_after_scrolling_the_page_and_the_frame(pointer_page, sites):
"""The page and the frame are both scrolled, so the element is where neither document's own coordinates say:
the click still lands on it. Below the fold of the frame, which is below the fold of the page; once in the
frame of B and once in the frame of C nested in it (scrolled too)."""
page = pointer_page
sites.route("B", "/tall", "<!doctype html>" + _grid(rows=14, cols=2) +
"<iframe id='c' src='%s' style='position:absolute;left:300px;top:20px;width:400px;height:300px;"
"border:0'></iframe><div style='position:absolute;top:1500px;width:1px;height:1px'></div>"
% sites.url("C", "/tall-c"))
sites.route("C", "/tall-c", "<!doctype html>" + _grid(rows=14, cols=2))
sites.route("A", "/scrolled", "<!doctype html><title>scrolled</title><body style='margin:0'>"
"<div style='height:900px'>spacer</div><iframe id='b' src='%s' width='900' height='400' "
"style='border:0'></iframe><div style='height:1200px'></div>" % sites.url("B", "/tall"))
page.goto(sites.url("A", "/scrolled"), wait_until="load")
outer = wait_frame(page, sites.url("B"), "/tall")
inner = wait_frame(page, sites.url("C"), "/tall-c")
page.evaluate("window.scrollTo(0, 700)")
outer.evaluate("window.scrollTo(0, 500)")
assert page.evaluate("window.scrollY") == 700 and outer.evaluate("window.scrollY") == 500
outer.locator("#r12c1").click()
assert outer.evaluate("window.landed") == [{"id": "r12c1", "trusted": True}]
inner.evaluate("window.scrollTo(0, 400)")
inner.locator("#r12c0").click()
assert inner.evaluate("window.landed") == [{"id": "r12c0", "trusted": True}]
assert outer.evaluate("window.landed") == [{"id": "r12c1", "trusted": True}]
# ---------------------------------------------------------------------------
# 8. screenshots
# ---------------------------------------------------------------------------
PINK, GREEN, BLUE, GOLD = (255, 0, 170), (0, 204, 68), (34, 85, 238), (255, 204, 0)
@pytest.fixture
def painted(sites):
sites.route("A", "/paint", "<!doctype html><title>paint</title><body style='margin:0;background:#fff'>"
"<iframe id='b' src='%s' style='position:absolute;left:50px;top:40px;width:300px;height:200px;"
"border:0'></iframe>" % sites.url("B", "/paint"))
sites.route("B", "/paint", "<!doctype html><body style='margin:0;background:#ff00aa'>"
"<div id='swatch' style='position:absolute;left:20px;top:30px;width:80px;height:60px;"
"background:#00cc44'></div>"
"<iframe id='c' src='%s' style='position:absolute;left:120px;top:20px;width:150px;height:120px;"
"border:0'></iframe>" % sites.url("C", "/paint"))
sites.route("C", "/paint", "<!doctype html><body style='margin:0;background:#2255ee'>"
"<div id='swatch' style='position:absolute;left:10px;top:10px;width:50px;height:40px;"
"background:#ffcc00'></div>")
return sites
def test_a_page_screenshot_shows_the_content_of_the_frames_of_other_sites(page, painted):
page.goto(painted.url("A", "/paint"), wait_until="load")
wait_frame(page, painted.url("C"), "/paint")
page.wait_for_timeout(500)
assert_other_process(page.main_frame, wait_frame(page, painted.url("B"), "/paint"))
_, _, pixel = decode_png(page.screenshot(scale="css"))
# outside the frame the page's own white; inside it the frame's pink; its swatch; the nested frame's blue
assert near(pixel(10, 10), (255, 255, 255)), pixel(10, 10)
assert near(pixel(50 + 5, 40 + 5), PINK), pixel(55, 45)
assert near(pixel(50 + 20 + 40, 40 + 30 + 30), GREEN), pixel(110, 100)
assert near(pixel(50 + 120 + 5, 40 + 20 + 5), BLUE), pixel(175, 65)
assert near(pixel(50 + 120 + 10 + 25, 40 + 20 + 10 + 20), GOLD), pixel(205, 90)
assert near(pixel(50 + 300 + 10, 40 + 10), (255, 255, 255)), "right of the frame"
@pytest.mark.parametrize("target,size,color", [("frame", (80, 60), GREEN), ("nested", (50, 40), GOLD)])
def test_a_locator_screenshot_of_an_element_in_a_frame_of_another_site(page, painted, target, size, color):
page.goto(painted.url("A", "/paint"), wait_until="load")
frame = {"frame": wait_frame(page, painted.url("B"), "/paint"),
"nested": wait_frame(page, painted.url("C"), "/paint")}[target]
page.wait_for_timeout(500)
width, height, pixel = decode_png(frame.locator("#swatch").screenshot(scale="css"))
assert (width, height) == size
for x, y in ((0, 0), (width - 1, height - 1), (width // 2, height // 2), (width - 1, 0)):
assert near(pixel(x, y), color), ((x, y), pixel(x, y))
def test_a_locator_screenshot_of_the_iframe_element_shows_the_frame(page, painted):
page.goto(painted.url("A", "/paint"), wait_until="load")
wait_frame(page, painted.url("C"), "/paint")
page.wait_for_timeout(500)
width, height, pixel = decode_png(page.locator("#b").screenshot(scale="css"))
assert (width, height) == (300, 200)
assert near(pixel(5, 5), PINK) and near(pixel(60, 60), GREEN) and near(pixel(125, 25), BLUE)
@@ -0,0 +1,323 @@
"""Workers made in frames of other sites, what a frame of another site keeps, and the frames that have no address.
Three sites (see `_fission_frames.py`): the top is A (`127.0.0.1`), the frame B (`localhost`), the frame C
(`127.0.0.2`) nested in B. With Fission each site is a content process of its own.
* Identity inside workers. A dedicated Worker made in the top, in the frame of B and in the frame of C (blob and
script-url workers) reports the same `navigator.userAgent`, `language`, `languages`, `hardwareConcurrency`,
`platform` and time zone as the window of the top and as the window that made it: a worker lives in the process
of the frame that made it, and its identity has to be declared there like the window's. The comparison reads an
absence as a mismatch, never as an agreement. A SharedWorker and a ServiceWorker are made from the frame of B:
the outcome asserted is what stock Firefox does there (see the docstrings).
* Cookies and storage. A cookie set by site B inside a frame of A appears in `context.cookies()` with B's domain;
what `document.cookie`, `localStorage` and `sessionStorage` show to B-in-A is what stock Firefox shows, and B
opened as a top page does not see them: storage is partitioned by top-level site, as in retail Firefox (stock
Playwright Firefox has that protection off; see the docstrings).
* Frames with no address of their own, at the top level and inside the frame of B: `srcdoc`, `about:blank`, a
`data:` url and a `sandbox`ed frame with and without `allow-scripts allow-same-origin`: they are in
`page.frames`, `evaluate` works where scripts run, and `frame_locator` reaches into them (see the docstrings
for what stock Firefox does with a sandbox that forbids scripts).
The first test proves the frames are in other processes, so the file cannot turn into a same-process suite.
"""
from __future__ import annotations
import json
import pytest
from _fission_frames import Sites, assert_other_process, launch, new_page, wait_for, wait_frame
pytestmark = pytest.mark.e2e
#: What a worker reads about the browser it runs in, as an object literal for its source.
IDENTITY = ("{userAgent: navigator.userAgent, language: navigator.language, languages: navigator.languages.join('|'),"
" hardwareConcurrency: navigator.hardwareConcurrency, platform: navigator.platform,"
" timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone}")
FIELDS = ("userAgent", "language", "languages", "hardwareConcurrency", "platform", "timeZone")
#: Run in a frame: make a dedicated worker (from a blob, or from the script of the frame's site) and return what it
#: reports, or the error.
WORKER_JS = """(kind) => new Promise(resolve => {
const source = 'postMessage(' + %s + ')';
let worker;
try {
worker = kind === 'blob' ? new Worker(URL.createObjectURL(new Blob([source], {type: 'text/javascript'})))
: new Worker('/identity-worker.js');
} catch (e) { resolve({error: String(e)}); return; }
worker.onmessage = e => resolve(e.data);
worker.onerror = e => resolve({error: 'worker error: ' + e.message});
setTimeout(() => resolve({error: 'timeout'}), 10000);
})""" % json.dumps(IDENTITY)
WINDOW_JS = "() => (%s)" % IDENTITY
@pytest.fixture
def sites():
with Sites() as s:
yield s
@pytest.fixture(scope="module")
def browser(firefox_binary):
with launch(firefox_binary) as browser:
yield browser
@pytest.fixture
def page(browser):
context, page = new_page(browser)
yield page
context.close()
def _absent(value):
return value is None or value == "" or (isinstance(value, str) and value.startswith("error"))
def mismatches(reference, other, fields=FIELDS):
"""Every field in which ``other`` differs from ``reference``; an absence on either side is a mismatch."""
problems = []
for field in fields:
if _absent(reference.get(field)):
problems.append("reference has no %s: %r" % (field, reference.get(field)))
elif _absent(other.get(field)):
problems.append("%s is absent (%r), the reference reads %r" % (field, other.get(field), reference[field]))
elif other[field] != reference[field]:
problems.append("%s = %r, the reference reads %r" % (field, other[field], reference[field]))
return problems
# ---------------------------------------------------------------------------
# identity inside workers
# ---------------------------------------------------------------------------
@pytest.fixture
def worker_pages(sites):
sites.route("A", "/workers", "<!doctype html><title>top</title><iframe id='b' src='%s' width='600' height='300'>"
"</iframe>" % sites.url("B", "/workers-b"))
sites.route("B", "/workers-b", "<!doctype html><title>b</title><iframe id='c' src='%s' width='400' height='150'>"
"</iframe>" % sites.url("C", "/workers-c"))
sites.route("C", "/workers-c", "<!doctype html><title>c</title>")
for site in ("A", "B", "C"):
sites.route(site, "/identity-worker.js", "postMessage(%s)" % IDENTITY, ctype="text/javascript")
return sites
def test_the_frames_are_in_other_processes(page, worker_pages):
page.goto(worker_pages.url("A", "/workers"), wait_until="load")
b = wait_frame(page, worker_pages.url("B"), "/workers-b")
assert_other_process(page.main_frame, b)
assert_other_process(b, wait_frame(page, worker_pages.url("C"), "/workers-c"))
@pytest.mark.parametrize("kind", ["blob", "url"])
def test_a_dedicated_worker_reports_the_identity_of_the_window_in_every_frame(page, worker_pages, kind):
page.goto(worker_pages.url("A", "/workers"), wait_until="load")
frames = {"top": page.main_frame,
"frame": wait_frame(page, worker_pages.url("B"), "/workers-b"),
"nested": wait_frame(page, worker_pages.url("C"), "/workers-c")}
reference = page.main_frame.evaluate(WINDOW_JS)
assert not mismatches(reference, reference), reference
problems = []
for name, frame in frames.items():
window = frame.evaluate(WINDOW_JS)
worker = frame.evaluate(WORKER_JS, kind)
problems += ["%s window: %s" % (name, p) for p in mismatches(reference, window)]
problems += ["%s %s worker: %s" % (name, kind, p) for p in mismatches(reference, worker)]
problems += ["%s worker against its own window: %s" % (name, p) for p in mismatches(window, worker)]
assert not problems, "identity differs between the top window and the frames and workers:\n " + "\n ".join(problems)
SHARED_WORKER_JS = """() => new Promise(resolve => {
try {
const worker = new SharedWorker('/shared-worker.js');
worker.port.onmessage = e => resolve({outcome: 'ok', identity: e.data});
worker.onerror = e => resolve({outcome: 'error', message: String(e.message || e)});
} catch (e) { resolve({outcome: 'throw', message: e.name + ': ' + e.message}); }
setTimeout(() => resolve({outcome: 'timeout'}), 10000);
})"""
SERVICE_WORKER_JS = """() => new Promise(resolve => {
try {
navigator.serviceWorker.register('/service-worker.js').then(
registration => navigator.serviceWorker.ready.then(ready => {
navigator.serviceWorker.onmessage = e => resolve({outcome: 'registered', scope: registration.scope,
identity: e.data});
(ready.active || registration.active).postMessage('who');
}),
e => resolve({outcome: 'rejected', message: e.name + ': ' + e.message}));
} catch (e) { resolve({outcome: 'throw', message: e.name + ': ' + e.message}); }
setTimeout(() => resolve({outcome: 'timeout'}), 15000);
})"""
def test_a_shared_worker_made_in_a_frame_of_another_site_reports_the_identity_of_the_top(page, worker_pages):
"""As stock Firefox does: a SharedWorker can be made from a frame of another site (its own site's worker
script), starts, and answers. What it reports about the browser is what the top window reads."""
worker_pages.route("B", "/shared-worker.js", "onconnect = e => { e.ports[0].postMessage(%s); };" % IDENTITY,
ctype="text/javascript")
page.goto(worker_pages.url("A", "/workers"), wait_until="load")
frame = wait_frame(page, worker_pages.url("B"), "/workers-b")
result = frame.evaluate(SHARED_WORKER_JS)
assert result["outcome"] == "ok", result
assert not mismatches(page.main_frame.evaluate(WINDOW_JS), result["identity"]), result
def test_a_service_worker_registered_from_a_frame_of_another_site_reports_the_identity_of_the_top(page, worker_pages):
"""As stock Firefox does: a frame of another site registers a ServiceWorker of its own site (scope the site's
root), it becomes active, and answers a message; what it reports about the browser is what the top window
reads."""
worker_pages.route("B", "/service-worker.js",
"self.addEventListener('install', e => self.skipWaiting());"
"self.addEventListener('activate', e => e.waitUntil(clients.claim()));"
"self.addEventListener('message', e => e.source.postMessage(%s));" % IDENTITY,
ctype="text/javascript", headers=[("Service-Worker-Allowed", "/")])
page.goto(worker_pages.url("A", "/workers"), wait_until="load")
frame = wait_frame(page, worker_pages.url("B"), "/workers-b")
result = frame.evaluate(SERVICE_WORKER_JS)
assert result["outcome"] == "registered", result
assert result["scope"] == worker_pages.url("B", "/"), result
assert not mismatches(page.main_frame.evaluate(WINDOW_JS), result["identity"]), result
# ---------------------------------------------------------------------------
# cookies and storage
# ---------------------------------------------------------------------------
@pytest.fixture
def storage_pages(sites):
read = "window.__r = {cookie: document.cookie, ls: localStorage.getItem('k'), ss: sessionStorage.getItem('k')};"
sites.route("A", "/storage", "<!doctype html><title>top</title><iframe id='b' src='%s'></iframe>"
% sites.url("B", "/storage-b"))
sites.route("B", "/storage-b", "<!doctype html><title>b</title><script>"
"document.cookie = 'jscookie=2; path=/'; localStorage.setItem('k', 'frame-ls');"
"sessionStorage.setItem('k', 'frame-ss'); %s</script>" % read,
headers=[("Set-Cookie", "hdrcookie=1; Path=/")])
sites.route("B", "/storage-own", "<!doctype html><title>own</title><script>%s</script>" % read)
# B as a top page writes a cookie and an item of its own; B in a frame of A reads them (they must not be there)
sites.route("B", "/storage-top-writes", "<!doctype html><title>top writes</title><script>"
"document.cookie = 'topcookie=3; path=/'; localStorage.setItem('top-only', 'top-ls');"
"window.__r = {cookie: document.cookie, top: localStorage.getItem('top-only')};</script>")
sites.route("B", "/storage-read-b", "<!doctype html><title>reads</title><script>"
"window.__r = {cookie: document.cookie, top: localStorage.getItem('top-only')};</script>")
sites.route("A", "/storage-read", "<!doctype html><title>top</title><iframe id='b' src='%s'></iframe>"
% sites.url("B", "/storage-read-b"))
return sites
def test_what_a_frame_of_another_site_stores_is_seen_by_the_frame_and_by_the_context(page, storage_pages):
"""As stock Firefox does: a cookie set by site B inside a frame of A (by a header and by script) is in
`context.cookies()` with B's domain, `document.cookie` of the frame shows both, and so do `localStorage` and
`sessionStorage` of the frame what the frame wrote; a second page of the context with the same frame sees
the same cookies and local storage, and the session storage of its own tab (the frame wrote it there too)."""
context = page.context
page.goto(storage_pages.url("A", "/storage"), wait_until="load")
frame = wait_frame(page, storage_pages.url("B"), "/storage-b")
assert frame.evaluate("window.__r") == {"cookie": "hdrcookie=1; jscookie=2", "ls": "frame-ls", "ss": "frame-ss"}
assert sorted((c["name"], c["domain"]) for c in context.cookies()) == [("hdrcookie", "localhost"),
("jscookie", "localhost")]
assert sorted(c["name"] for c in context.cookies(storage_pages.url("B"))) == ["hdrcookie", "jscookie"]
assert context.cookies(storage_pages.url("A")) == []
second = context.new_page()
second.goto(storage_pages.url("A", "/storage"), wait_until="load")
again = wait_frame(second, storage_pages.url("B"), "/storage-b")
assert again.evaluate("window.__r") == {"cookie": "hdrcookie=1; jscookie=2", "ls": "frame-ls", "ss": "frame-ss"}
def test_storage_of_site_b_is_partitioned_between_a_frame_of_a_and_b_as_a_top_page(page, storage_pages):
"""The retail outcome, not stock Playwright's: cookies and web storage are partitioned by the top-level site.
What site B wrote inside a frame of A is not visible to B opened as a top page: its `document.cookie` is empty
and its `localStorage` item is null (`context.cookies()` still lists B's cookies, with B's domain, because it
reads the whole jar). The reverse holds too: a cookie and a local-storage item that B wrote as a top page are
not visible to B inside the frame of A. The session storage of the top page is empty in both cases.
Why the reference here is the retail Firefox and not stock Playwright Firefox: the reference of this project
is what a page reads in a Firefox a user installed, and retail Firefox partitions third-party cookies and
storage by top-level site (Total Cookie Protection). Playwright's own Firefox ships with that protection off
and shows the stored values to B as a top page (observed with Playwright 1.62: `document.cookie` is
`hdrcookie=1; jscookie=2` and the item is `frame-ls`), which is not what a page sees in a real browser, so
its answer is not the one asserted."""
context = page.context
page.goto(storage_pages.url("A", "/storage"), wait_until="load")
wait_frame(page, storage_pages.url("B"), "/storage-b")
own = context.new_page()
own.goto(storage_pages.url("B", "/storage-own"), wait_until="load")
assert own.evaluate("window.__r") == {"cookie": "", "ls": None, "ss": None}
assert sorted(c["name"] for c in context.cookies(storage_pages.url("B"))) == ["hdrcookie", "jscookie"]
# the reverse: B writes as a top page, then is framed by A and reads
own.goto(storage_pages.url("B", "/storage-top-writes"), wait_until="load")
assert own.evaluate("window.__r") == {"cookie": "topcookie=3", "top": "top-ls"}
reader = context.new_page()
reader.goto(storage_pages.url("A", "/storage-read"), wait_until="load")
frame = wait_frame(reader, storage_pages.url("B"), "/storage-read-b")
# B inside A reads its own partition: the two cookies the frame wrote above are there, what B wrote as a top page
# (`topcookie`, the `top-only` item) is not.
assert frame.evaluate("window.__r") == {"cookie": "hdrcookie=1; jscookie=2", "top": None}
# ---------------------------------------------------------------------------
# frames with no address of their own
# ---------------------------------------------------------------------------
INNER = "&lt;p id=x&gt;%s&lt;/p&gt;&lt;script&gt;window.v=1&lt;/script&gt;"
SPECIAL = ('<iframe id="srcdoc" srcdoc="%s"></iframe>' % (INNER % "in srcdoc")
+ '<iframe id="blank"></iframe>'
+ '<iframe id="data" src="data:text/html,%s"></iframe>' % (INNER % "in data")
+ '<iframe id="sb0" sandbox srcdoc="%s"></iframe>' % (INNER % "sb0")
+ '<iframe id="sb1" sandbox="allow-scripts allow-same-origin" srcdoc="%s"></iframe>' % (INNER % "sb1")
+ '<iframe id="sb2" sandbox="allow-scripts" srcdoc="%s"></iframe>' % (INNER % "sb2"))
#: id -> (url of the frame, `window.v` in it, text of #x). `window.v` is 1 where the document's script ran;
#: a sandbox without `allow-scripts` runs none, but `evaluate` still works there and answers undefined.
SPECIAL_FRAMES = {
"srcdoc": ("about:srcdoc", 1, "in srcdoc"),
"blank": ("about:blank", None, None),
"data": (None, 1, "in data"),
"sb0": ("about:srcdoc", None, "sb0"),
"sb1": ("about:srcdoc", 1, "sb1"),
"sb2": ("about:srcdoc", 1, "sb2"),
}
@pytest.fixture
def special_pages(sites):
sites.route("A", "/special", "<!doctype html><title>special</title>" + SPECIAL)
sites.route("B", "/special", "<!doctype html><title>special b</title>" + SPECIAL)
sites.route("A", "/special-in-b", "<!doctype html><title>top</title><iframe id='b' src='%s'></iframe>"
% sites.url("B", "/special"))
return sites
@pytest.mark.parametrize("where", ["top", "inside_b"])
def test_special_frames_are_listed_evaluated_and_reached_by_frame_locator(page, special_pages, where):
"""As stock Firefox does: `srcdoc` and every `sandbox`ed srcdoc frame is `about:srcdoc`, the empty one is
`about:blank`, the `data:` one keeps its url; all are in `page.frames` under their parent, named by their id;
`evaluate` works in all of them and finds `window.v` where the document's script could run (not in the
sandbox without `allow-scripts`, not in the empty frame); `frame_locator` reaches the text inside each, in
the empty frame once something is written there; the same at the top level and inside a frame of B."""
path = "/special" if where == "top" else "/special-in-b"
page.goto(special_pages.url("A", path), wait_until="load")
owner_site = "A" if where == "top" else "B"
owner = wait_frame(page, special_pages.url(owner_site), "/special")
if where == "inside_b":
assert_other_process(page.main_frame, owner)
expected_count = 1 + (where == "inside_b") + len(SPECIAL_FRAMES)
assert wait_for(page, lambda: len(page.frames) == expected_count), [(f.name, f.url) for f in page.frames]
inner = {f.name: f for f in page.frames if f.parent_frame is owner}
assert sorted(inner) == sorted(SPECIAL_FRAMES), [(f.name, f.url) for f in page.frames]
scope = page.frame_locator("#b") if where == "inside_b" else page
for frame_id, (url, value, text) in SPECIAL_FRAMES.items():
frame = inner[frame_id]
if url is None:
assert frame.url.startswith("data:text/html,"), frame.url
else:
assert frame.url == url, (frame_id, frame.url)
assert frame.evaluate("window.v") == value, frame_id
if frame_id == "blank":
frame.evaluate("document.body.innerHTML = '<p id=x>written</p>'")
text = "written"
assert scope.frame_locator("#" + frame_id).locator("#x").inner_text() == text, frame_id