Compare commits

...
Author SHA1 Message Date
feder-cr 455d5619e5 hunt: record the page-bytes reference of the core 64.71.0 on Windows and Linux (2 launches each)
Hunt only, never merged. One workflow on a push to its own branch: windows-2022 and ubuntu-24.04
(xvfb), two at a time, installs this checkout with the core of its pin (checked to be 64.71.0),
fetches the published engine, launches the persona of the e2e twice, reads the page-bytes probe,
and writes tests/data/page_bytes_<os>.json with every key equal in both launches (PNG keys on
decoded pixels). Unstable keys are listed apart and left out. The log carries the reference between
RECORD-BEGIN and RECORD-END, and the artifact the file to copy.
2026-11-15 02:04:44 +01:00
feder-cr aa53d6ea06 tests: the page-bytes probe reads WebGPU features and limits by name
Array.from(adapter.features) and for-in over adapter.limits threw "Xray wrapping of iterators not
supported" in the page (run 43652292533), so the reference held an error string instead of the
adapter. Both are read by the names of the WebGPU specification (has, a property read). The
Windows reference drops gpu.webgpu.error; features and limits are recorded with the rest.
2026-11-15 01:54:44 +01:00
feder-cr 4b2fb63fe6 tests: software compositing is declared: the compositor, the GPU process CPU and the bytes a page reads
The core now declares software compositing on every machine (the compositing entries of the
feature-status table carry the VM decision; on Windows gfx.webrender.software=true and
gfx.webrender.software.d3d11=false). One e2e file, three tests, Linux and Windows:

1. windowUtils.layerManagerType of the engine's windows, read in chrome scope through Marionette,
   is "WebRender (Software)" (Troubleshoot.snapshot().graphics throws on this engine, so the
   provider's own two properties are read), and the declared table and prefs say so;
2. the GPU process uses under 1.5 s of CPU on the fixed 10-scene loop of one browser (Windows
   runner: 0.32 s declared, 2.7-4.2 s not; runs 43652292533 and 43642744101);
3. the 86 keys of the page-bytes probe plus canvas 2D scenes added for the canvas blocklist
   (drawImage scaled with smoothing off/low/medium/high, text with linear/radial/conic gradients)
   equal tests/data/page_bytes_<os>.json, PNGs compared on decoded pixels (every PNG carries a
   per-launch deBG chunk).

The Windows reference is taken from run 43652292533 (75 stable keys, 6 of the 11 PNG keys); what it
lacks is recorded by the first run on the engine of the reference, whose failure prints the entries.
Registered as wrapper.e2e.compositing (G2, both systems, 3 tests) and wrapper.unit.compositing (G1,
17 tests, the helpers on known inputs).
2026-11-15 01:53:32 +01:00
Federico Elia 83afc6c8d5 tests: the leak census imports nothing of the package (#500)
The census answers from sys.modules, so the jobs that install pytest alone (version) do not import the core.
2026-11-15 00:39:24 +01:00
feder-cr 163315c114 tests: the leak census imports nothing when no starter could have been built, so it runs in jobs without invisible_core 2026-11-15 00:26:20 +01:00
Federico Elia 91e69710eb perf: connect() starts no thread on the event loop (#497)
The four workers of a connection are built on the loop and started by the connection's one thread starter, the same one the engine's reader uses.
2026-11-15 00:07:27 +01:00
feder-cr cf328bf481 perf: one ThreadStarter per connection, owned by the server
The previous commit gave each browser two starter threads (the
BrowserDispatcher's for the reader, the transport's for the workers). Now the
connection's server (dispatcher.Server) owns a single ThreadStarter, built on
first use (Server.thread_starter) and stopped once, in Server.shutdown, which
the transport's request_stop already calls.

The transport starts its four workers through it (start_built, with a
per-thread failure callback that ends the transport). BrowserDispatcher holds
a ThreadStarterLease on it instead of building a starter: start() while the
browser's connection lives, nothing after the connection's close listener ran,
the same semantics the browser's own starter had. A browser that never needs a
thread makes none.

Remote: remote._SharedServer is a Server, so the shared server owns the one
starter (one browser per served launch; contexts and clients come and go under
it, shutdown ends it). Several browsers launched under one local server share
the one thread, which is why the lease, not the starter, ends with a browser's
connection.

Measured, live threads per browser right after a launch (transport.connect, a
BrowserDispatcher over the unit fixture's engine, one adoption started):
65b7a3c: 6 (invpw-thread-starter x2, juggler x4); now: 5 (starter x1,
juggler x4). Same at 4 browsers: 24 -> 20. All gone after close.

Tests that built a Server and only closed the connection now shut the server
down; the fake servers of the transport tests derive from Server.
2026-11-14 23:54:52 +01:00
feder-cr 65b7a3c3bc tests: the census counts a ThreadStarter from its construction, not from its thread
ThreadStarter now begins its own thread without waiting for it
(_thread.start_new_thread running Thread.start), so right after the constructor
the starter can be in no threading.enumerate(). The census of live
"invpw-thread-starter" threads then saw 0 leaks where a module built 2 (Linux
runner, 3 of 3 jobs: the inner pytest passed). Not a rename, not a wrong
count: a census of threads cannot see a thread that has not begun.

Fix at the source of the count: ThreadStarter keeps the set of starters built
and not yet ended (open_starters()), and the census counts that. The "no
Thread.start on the caller" guarantee is untouched.

Test, red on the old census (Thread.start slowed to 300 ms: the census sees 0
right after the constructor, expected 1): the census counts a starter whose
thread has not begun.
2026-11-14 23:30:58 +01:00
feder-cr 05190ed5e9 comment: the starter is called ThreadStarter now 2026-11-14 22:52:58 +01:00
feder-cr cfbf1889a8 perf: one ThreadStarter, shared, for the reader and for the transport's workers
Replaces the second bootstrapper (_thread.start_new_thread running a loop that
starts the workers) with the ThreadStarter the engine's reader already uses, so
one mechanism lives in one place: src/invisible_playwright/_juggler/_threads.py,
imported by server.py and transport.py.

ThreadStarter's own construction no longer calls Thread.start on its caller
either: its thread is begun by _thread.start_new_thread running Thread.start, so
the wait for the starter to run happens on that raw thread. It is still a
threading.Thread named invpw-thread-starter (alive a moment after the
constructor returns). connect() builds the four juggler-N threads, queues them
with start_built() and returns; request_stop stops the starter; a start that
fails ends the transport.

Tests: the connect() test stays red on origin/main (1202 ms against the 50 ms
bound) and a new one covers building the starter with Thread.start slowed to
300 ms. The two tests that import the starter now import it from _threads.
2026-11-14 22:52:50 +01:00
feder-cr 2d2204898e perf: InProcessTransport.connect starts no thread on the event loop
connect() is a coroutine of the user's loop and Thread.start() blocks until
the new thread runs. Measured on Windows CI (py-spy, 4 browsers in one
process under CPU load), the 4 "juggler-N" starts held the loop ~200 ms per
launch, 4.4% of the main thread's wall time.

Shape: connect() only BUILDS the 4 Thread objects (so request_stop still
puts one sentinel per worker) and begins one bootstrapper with
_thread.start_new_thread, which returns once the OS made the thread and
waits for nothing. A threading.Thread for the bootstrapper would be one more
Thread.start on the loop, so it is not used. The bootstrapper starts the
workers. Messages sent before a worker runs wait in the queue, as send()
already relied on; replies are matched by id, so no ordering is lost.

Workers are not reduced: a blocking operation must not hold up the others,
and nothing in the code or tests proves fewer suffice. A start that fails
stops the transport instead of leaving calls waiting; wait_until_stopped
joins only workers that were started.

Test (red on old code: connect took 1202 ms vs the 50 ms bound with
Thread.start slowed to 300 ms): tests/test_connect_does_not_start_threads_on_the_loop.py.
2026-11-14 22:52:35 +01:00
feder-cr 384351d4a3 Release 0.52.1: expose_function/expose_binding, element screenshot, init script once, CORS preflight not reported 2026-11-14 21:23:50 +01:00
feder-cr a14da2127e Merge #468 into release/0.52.1 2026-11-14 21:23:24 +01:00
feder-cr b60b5c5e8c Merge #471 into release/0.52.1
# Conflicts:
#	CHANGELOG.md
2026-11-14 21:23:24 +01:00
feder-cr 252036e2fc Merge #470 into release/0.52.1
# Conflicts:
#	CHANGELOG.md
2026-11-14 21:23:23 +01:00
feder-cr 0f7a9a2905 Merge #469 into release/0.52.1
# Conflicts:
#	CHANGELOG.md
2026-11-14 21:23:22 +01:00
feder-cr 112467f5ad Merge #467 into release/0.52.1
# Conflicts:
#	CHANGELOG.md
2026-11-14 21:23:21 +01:00
feder-cr 22d8abc9ba Merge #458 into release/0.52.1 2026-11-14 21:23:12 +01:00
feder-cr a743dbbbf7 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.
2026-11-14 21:23:11 +01:00
feder-cr f7873501e2 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.
2026-11-14 21:23:11 +01:00
feder-cr bcf47c7dde 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.
2026-11-14 21:23:11 +01:00
feder-cr fcfbed215e 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.
2026-11-14 21:23:11 +01:00
feder-cr b0b4f02d7c 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.
2026-11-14 21:23:11 +01:00
feder-cr d842a35ffa page.expose_function / expose_binding and context.expose_function / expose_binding
All four were refused ("not wired", "no method 'exposeBinding'"). The page calls a Python function and gets a promise: the value, a
rejection when the Python function raised, an await when it is async.

The page sees the function and nothing else. One engine binding per exposed name (Browser.addBinding for a context, Page.addBinding for
a page), under a native name chosen per session. The engine puts the native function on the window of every document, present and future,
in every process, before any script of the page, and runs the binding's script. The script takes the native function off the window, keeps
it in a closure, defines the function (an ordinary function; its source says nothing of what it is for) and hands the engine the function
that answers a call. Answers go through Runtime.callFunction on it. No init script, no controller, nothing run by this server in the
documents.

An engine without Page.addBinding and the binding that hands its end over is refused with a clear sentence: there is no fallback to a name
on the window. The engine is read from its own files (protocol schema and Runtime).

Calls are announced to the client in order by one worker per page, started by the browser's thread starter (never on the reader), and not
before the client has been told the address of the document that called: a script that calls the function in its first lines ran before the
commit reached the client and named a frame with an empty url. A name nobody exposed here is answered with an error instead of leaving the
page's promise waiting.

Limit: arguments and results cross as JSON (undefined, functions and NaN arrive as null).

Tests: e2e (before the load and across a navigation, after the load, async and a Python error, source page/frame, not on another page, on
the context for a page that exists, a page to come and their frames, disposed; the window of a page with an exposed function has its name
more and no symbol more, in the top, in a frame of another site, in a nested one, after a navigation and after document.open(); name, length,
own properties, descriptor, prototype and place among the keys are those of a function the page defined; neither its source nor the stack of an
error raised from it names the driver; a worker gets nothing) and the refusal of an engine that lacks what the functions need.
2026-11-14 20:07:15 +01:00
feder-cr 1832ea6323 Locator.screenshot / ElementHandle.screenshot: a picture of the element
The wrapper had no `screenshot` on an element handle ("ElementHandle has no method 'screenshot'"). The element is scrolled in, its box is
read from the engine's content quads (the main frame's viewport space, whatever frame the element is in, across processes), the main
frame's scroll is added to reach document coordinates, and the page's own screenshot takes that rectangle, so the type, the quality and
the scale have one path. An element with no layout box (display: none, detached) answers "Element is not visible".

Tests: an element in view, one far below the fold, one inside a frame below that frame's fold, and the <iframe> element itself; the
element that is not there. The Fission frame tests for a frame of another site, a nested one and the <iframe> element (draft #468) pass:
4 of 4 (3 were red on main).
2026-11-14 20:07:12 +01:00
feder-cr 1b974cd964 A context init script added after a page exists runs once, not twice
op_context_init_script registered the script on both sides: in the browser (Browser.setInitScripts, which the engine applies to every
page of the context, the pages already open included) and again in the own list of each open page. The comment said the open pages
do not re-read the context's list; they do. A page that existed when the script was added ran it twice in every later document; a
page opened afterwards ran it once, so any test that adds the script first passed. Found by the Fission frame tests (the document of
the top page saw ["init","init"]).

The script is registered once, in the browser, and removed from there. Test (e2e, hermetic): a page that exists before the script and
one opened after it each see ["init"], in the first document and in the next one. Red on the old code (['init', 'init']).
2026-11-14 16:06:13 +01:00
feder-cr 2c8bfa12da A CORS preflight is not a request the client hears of, as on stock Firefox
Playwright's own server drops an OPTIONS request that no route holds before the client can see it (ffNetworkManager
_onRequestWillBeSent: `if (event.method === "OPTIONS" && !event.isIntercepted) return;`). Ours reported it: a page with
preflighted fetches showed more requests than on stock Firefox, 10 OPTIONS a page on cnbc.com and 18 on scmp.com (three
pairs, our engine and Playwright's Firefox side by side), in page.on("request"), in a route and in any request counter.

The server drops the same requests now, at the place where the event is turned into a request of the client; the response and the
end of a dropped request find no request and are dropped with it.

Test (e2e): a page at one origin fetches another with a header that needs a preflight; the client hears the document and the two
fetches and no OPTIONS, with and without a context route. Red before.
2026-11-14 16:06:13 +01:00
feder-cr 8d48c4a472 Remove scripts that no test round runs
- scripts/check_unresolved_names.py: replaced by the ruff F821/F811/F601 step in .github/workflows/tests.yml.
- scripts/bench_transport.py: one-off measurement that asserts nothing.
- scripts/diff_protocol.py: needs the Node driver arm, which was removed.
- scripts/judge_both_transports.py: needs the Node driver arm, which was removed.
- tests/gates/prefs_byte_parity.py: compares with the removed driver's prefs writer.
- tests/gates/driver_prefs_rules.json: frozen rules for that comparison, nothing else reads it.

References to these files in comments, docstrings and THIRD_PARTY_FORK.md are reworded.
2026-11-14 16:00:58 +01:00
50 changed files with 4799 additions and 1322 deletions

No files matched your search

@@ -0,0 +1,92 @@
# ─────────────────────────────────────────────────────────────────────────────
# page-bytes-reference-hunt.yml - HUNT ONLY, never merged: record the "before" reference of what a page reads, per operating system.
#
# The e2e tests/test_software_compositing_is_declared_e2e.py (branch tests/software-compositing-declared) compares what a page reads (the
# probe tests/page_bytes_probe.js: canvas 2D, WebGL 1 and 2, WebGPU, text, the declared values) with tests/data/page_bytes_<os>.json. That
# reference is the bytes of the engine BEFORE the core declares software compositing, so it must be recorded with the core the release
# branch pins today (invisible-core 64.71.0), by a run of GitHub and not by hand.
#
# One job per system (windows-2022, ubuntu-24.04 under xvfb as e2e.yml runs it), two at a time: install this checkout (the core of its pin),
# fetch the published engine, launch the browser twice with the persona of the test (seed 42, en-US, Europe/Rome), read the probe, and write
# page_bytes_<os>.json with every key that is equal in both launches; a key that is not is listed apart (unstable.json, summary.txt, the job
# summary) and left out. The log carries the reference between RECORD-BEGIN <os> and RECORD-END; the artifact holds the file to copy into
# tests/data/ and the raw values of each launch.
#
# Nothing of the product is changed. Starts on a push to its own branch only.
# ─────────────────────────────────────────────────────────────────────────────
name: page bytes reference hunt
on:
push:
branches: [hunt/page-bytes-reference]
permissions:
contents: read
concurrency:
group: page-bytes-reference-hunt-${{ github.ref }}
cancel-in-progress: true
# Engine and GeoIP downloads go through the release API with this token (as in e2e.yml).
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
hunt:
name: "hunt (${{ matrix.os }}, page bytes of the core 64.71.0, 2 launches)"
runs-on: ${{ matrix.os }}
timeout-minutes: 40
strategy:
fail-fast: false
max-parallel: 2
matrix:
os: [windows-2022, ubuntu-24.04]
defaults:
run:
shell: bash
env:
PYTHONUNBUFFERED: "1"
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install the wrapper (and its core, by the pin of this checkout)
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]"
# Playwright ONLY as a system tool, for `playwright install-deps firefox` on Linux (as e2e.yml does).
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
- name: The core is the one this reference is for (invisible-core 64.71.0, the pin of the release branch)
run: |
PIN=$(grep -oE 'invisible_core==[0-9.]+' pyproject.toml | head -1 | cut -d= -f3)
GOT=$(python -c "from importlib.metadata import version; print(version('invisible-core'))")
echo "pyproject pins invisible-core $PIN, installed $GOT"
test "$PIN" = "$GOT"
test "$GOT" = "64.71.0"
- name: System deps (xvfb + Firefox runtime libs)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y xvfb
sudo "$(which python)" -m playwright install-deps firefox
- name: Fetch the published firefox binary
run: echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The GeoIP database (made by the repository, same bytes every run)
run: python scripts/ci_lab_geoip.py build
- name: Record the page bytes (2 launches)
run: |
if [ "$RUNNER_OS" = "Linux" ]; then RUN="xvfb-run -a"; else RUN=""; fi
$RUN python -u scripts/hunt_page_bytes_reference.py --binary "$FF" --launches 2 --out "$RUNNER_TEMP/pbref"
- name: Close every Firefox left
if: always()
run: |
if [ "$RUNNER_OS" = "Windows" ]; then taskkill //F //IM firefox.exe //T > /dev/null 2>&1 || true; else pkill -9 firefox || true; fi
- name: Upload the reference
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: page-bytes-reference-${{ matrix.os }}-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ runner.temp }}/pbref
if-no-files-found: warn
retention-days: 14
+15
View File
@@ -6,6 +6,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
## [0.52.1] - 2026-11-14
Same pin as 0.52.0 (invisible-core 64.71.0).
### Added
- `page.expose_function`, `page.expose_binding`, `context.expose_function` and `context.expose_binding`, as in Playwright: the page calls a Python function and gets a promise (the value, a rejection when the function raised, an await when it is async). The page sees the function and nothing else (no name of ours on the window, no init script); an engine without `Page.addBinding` is refused with a clear sentence. Arguments and results cross as JSON. (#471)
- `Locator.screenshot()` and `ElementHandle.screenshot()`: a picture of the element, as in Playwright, in the page, in a frame of another site and in a frame nested in it. (#470)
### Fixed
- A context init script added after a page exists runs once in it, not twice. (#469)
- A CORS preflight (an OPTIONS request that no route holds) is no longer reported to the client, as in Playwright's own server: `page.on("request")`, `route` and a request counter hear of one request fewer for each preflighted fetch of the page. (#467)
### Changed
- Comments, the fork notes and one test message no longer point at scripts that were deleted (the transport comparison scripts and the prefs byte-parity gate: no round ran them). No behaviour changes. (#458)
## [0.52.0] - 2026-11-14
### Changed
+3 -1
View File
@@ -9,5 +9,7 @@
{"id": "wrapper.e2e.realness", "giro": "G2", "os": ["linux", "windows"], "min_tests": 32, "exact": true, "tests": ["tests/test_realness_behind_a_declared_exit_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "The realness check without a real proxy: six declared exits, the values a page reads, and the roads. Linux runs as root without xdist like the DoH suite (the resolver trap); on Windows the trap does not exist and the assertion on the system resolver is the only one omitted."},
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 249, "exact": true, "tests": ["tests/test_the_server_says_nothing_about_the_launch_counter.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py", "tests/test_preload_newtab_reaches_the_core_only_when_asked.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_realness_helpers.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_host_address_helper.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_fake_doh_answers.py", "tests/test_doh_session_prefs_unit.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_witness_hears_a_direct_send.py", "tests/test_the_egress_sink_helpers.py", "tests/test_the_lab_ca_and_its_ocsp_leaf.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added. The sink of the egress gate (tests/test_the_egress_sink_helpers.py, 20): the engine's log (the same on Linux and Windows) and the witness read on known inputs, and a blind log that must raise, never answer 'nothing'. The lab CA of its OCSP case (tests/test_the_lab_ca_and_its_ocsp_leaf.py, 17; tests/test_the_fake_doh_answers.py +1, the DoH serving a lab-CA leaf): the leaf's AIA, trusted and untrusted issuers, the responder, the xpcshell step."},
{"id": "wrapper.e2e.page", "giro": "G2", "os": ["linux", "windows"], "min_tests": 115, "exact": true, "tests": ["tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_popup_destinations_e2e.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_route_superseded_e2e.py"], "marker": "e2e", "needs_root": false, "note": "114 = 100 + the 14 of test_a_page_that_moves_on_e2e.py (a navigation the page overtook with location.replace ends; the engine fix 860ef8a6d9 is proved by it). 100 counted at the collection; was 96 = 10+32+16+34+4 before the popup tests of 6200bc2). A page is handed over when the engine says Page.ready; a popup reaches the client (link, noopener, window.open; own site and another; with and without a route; in-process and over launch_server) as Playwright's does; a superseded route. Needs the candidate binary, and the stock Playwright client of the dev extra."},
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 72, "exact": true, "tests": ["tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_the_hand_over_of_a_popup_holds_under_concurrency.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py"], "marker": "unit", "needs_root": false, "note": "72 = 44 + 3+9+5+1+10 of the popup hand-over (24 counted at the collection before; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."}
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 72, "exact": true, "tests": ["tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_the_hand_over_of_a_popup_holds_under_concurrency.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py"], "marker": "unit", "needs_root": false, "note": "72 = 44 + 3+9+5+1+10 of the popup hand-over (24 counted at the collection before; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."},
{"id": "wrapper.e2e.compositing", "giro": "G2", "os": ["linux", "windows"], "min_tests": 3, "exact": true, "tests": ["tests/test_software_compositing_is_declared_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The engine DECLARES software compositing on every machine (core: the compositing entries of zoom.stealth.gfx.feature_status carry the VM decision, and on Windows gfx.webrender.software=true, gfx.webrender.software.d3d11=false). 3 = (1) the compositor read from a privileged context is 'WebRender (Software)' on Windows and on Linux (windowUtils.layerManagerType of each window: Troubleshoot.snapshot().graphics throws on this engine, `ext is null`, so it is not the route); (2) the GPU process uses under 1.5 s of CPU on the fixed 10-scene loop of one browser (Windows runner: 0.32 s declared, 2.7-4.2 s not, runs 43652292533 and 43642744101; on Linux it is held to the bound if a GPU process exists); (3) the 86 keys of the page-bytes probe plus the canvas 2D scenes (drawImage scaled with smoothing off/low/medium/high, text with linear/radial/conic gradients) equal tests/data/page_bytes_<os>.json, PNGs on decoded pixels. EXPECTED RED on the core 64.71.0 (tests 1 and 2 on Windows). The reference of Windows holds the 75 stable keys and 6 of the 11 PNG keys of run 43652292533; the five other PNG keys and the new canvas keys, and all of Linux, are written from the first run on the engine of the reference (the failure of test 3 prints RECORD-BEGIN ... RECORD-END with the entries to merge): a reference that is not complete is red, never skipped."},
{"id": "wrapper.unit.compositing", "giro": "G1", "os": ["linux", "windows"], "min_tests": 17, "exact": true, "tests": ["tests/test_the_page_bytes_reference_compares_decoded_pixels.py"], "marker": "unit", "needs_root": false, "note": "The helpers of wrapper.e2e.compositing on known inputs, no browser: the PNG compared on decoded pixels (another deBG chunk and compression are the same, one pixel is not, every scanline filter), the comparison with a reference (changed, missing and extra keys named, the entry to record), the type of an engine process and the CPU of a window, and the shape of the committed Windows reference."}
]
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "invisible_playwright"
version = "0.52.0"
version = "0.52.1"
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
readme = "README.md"
requires-python = ">=3.11"
-132
View File
@@ -1,132 +0,0 @@
"""How much does answering the protocol IN PROCESS actually cost?
⛔ THE QUESTION IS NARROW ON PURPOSE. Not "is the Python path faster than the
Node driver" - that comparison is dominated by the browser and would answer a
different question. This measures ONLY the machinery this package adds between
`Channel.send` and the code that talks to Juggler: building the message dict,
the queue, the worker-thread hop, the reply, and `call_soon_threadsafe` back
onto the loop.
That is the thing the owner asked about on 2026-08-28: inside one process,
serialising to yourself looks like waste. Whether it IS waste depends on how it
compares to the round trip it wraps, and this project decides that kind of
question with a number.
⛔ NO BROWSER, and that is what makes this trustworthy. A fake server answers
instantly, so what is left in the measurement is the transport and nothing
else. It also means the result does not depend on the machine being quiet in
the way a browser measurement does - though a loaded machine still widens the
tail, which is why the median is reported next to the mean.
python scripts/bench_transport.py
python scripts/bench_transport.py --giri 20000
"""
from __future__ import annotations
import argparse
import asyncio
import pathlib
import statistics
import sys
import time
ROOT = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "src"))
#: What a real Juggler round trip costs, measured on 2026-08-27 with the
#: shipped binary. It is the denominator: the transport's cost only means
#: something as a fraction of the work it wraps.
#: ⛔ `Runtime.evaluate("1")` and NOT `Heap.collectGarbage`, which was used once
#: as a "bare command" and actually collects garbage - 26,8 ms of browser work
#: attributed to the transport.
JUGGLER_ROUND_TRIP_MS = 2.4
class FakeServer:
"""Answers instantly, so only the transport is being timed."""
def __init__(self) -> None:
self.transport = None
def attach(self, transport) -> None:
self.transport = transport
def shutdown(self) -> None:
pass
def handle(self, message):
return {"value": message["params"].get("n")}
async def run(rounds: int) -> int:
from invisible_playwright._juggler.transport import InProcessTransport
loop = asyncio.get_running_loop()
transport = InProcessTransport(loop, FakeServer())
await transport.connect()
pending = {}
def on_message(message):
future = pending.pop(message.get("id"), None)
if future is not None and not future.done():
future.set_result(message)
transport.on_message = on_message
async def one(index: int):
future = loop.create_future()
pending[index] = future
transport.send({"id": index, "guid": "x", "method": "noop",
"params": {"n": index},
"metadata": {"apiName": "bench"}})
return await future
# ⛔ A warm-up that is DISCARDED: the first calls pay for thread start-up
# and for the first allocation of every structure, and folding those into
# the average is how a microbenchmark reports a number nobody can reproduce.
for i in range(200):
await one(i)
samples = []
for i in range(rounds):
start = time.perf_counter()
await one(200 + i)
samples.append((time.perf_counter() - start) * 1000.0)
transport.request_stop()
await transport.wait_until_stopped()
samples.sort()
media = statistics.fmean(samples)
mediana = samples[len(samples) // 2]
p95 = samples[int(len(samples) * 0.95)]
print("giri utili %d" % len(samples))
print("media %.4f ms" % media)
print("mediana %.4f ms" % mediana)
print("p95 %.4f ms" % p95)
print("p99 %.4f ms" % samples[int(len(samples) * 0.99)])
print()
print("un giro Juggler vero %.2f ms (misurato 2026-08-27)"
% JUGGLER_ROUND_TRIP_MS)
quota = 100.0 * mediana / JUGGLER_ROUND_TRIP_MS
print("il transport pesa %.1f%% di una chiamata vera" % quota)
print()
if quota < 10:
print("VERDETTO: il transport NON e' il costo. Togliere thread e coda "
"andrebbe fatto per semplicita', se mai, non per velocita'.")
else:
print("VERDETTO: il transport pesa abbastanza da giustificare il "
"refactor asincrono.")
return 0
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--giri", type=int, default=5000)
a = p.parse_args()
return asyncio.run(run(a.giri))
if __name__ == "__main__":
sys.exit(main())
+2 -2
View File
@@ -100,8 +100,8 @@ def _classes(tree: ast.AST) -> dict:
#: next step. The failure it would cause is silent and backwards: an `async
#: def` operation is absent from `_methods`, so `reachable` returns an EMPTY
#: known-set for it, and every field that operation legitimately reads gets
#: reported as ignored. Same tuple as `check_unresolved_names.py`'s
#: `_FUNCTIONS`, for the same reason.
#: reported as ignored. Both function kinds are listed for the same reason as in any
#: AST walk over operations.
_FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef)
-243
View File
@@ -1,243 +0,0 @@
"""A method that uses a name it never has: the NameError nobody ran into yet.
⛔ IT CAUGHT TWO REAL DEFECTS THE MOMENT IT WAS WRITTEN, both of the same shape
and both invisible to every other check in this repo:
* `Actions._set_checked` passed `frame_id` to its retry loop without ever
taking it as a parameter, while `check()` and `uncheck()` accepted the
argument and dropped it. Every `page.check()` on the Python transport died
with `Page.check: name 'frame_id' is not defined` - and the transport judge
reported it as an ENGINE defect, because the test that exercises it pins the
transport itself and therefore fails identically on both arms.
* `Actions.drag_and_drop` did the same thing twice in one function.
⛔ WHY THE SUITE DID NOT SEE IT. A `NameError` inside a method is not a syntax
error and not an import error: the module loads, the class builds, the name
resolves at CALL time. So the whole file is green until somebody calls that one
method, and the two above sat in a package with 500 passing tests.
**What it does NOT do.** It does not type-check, it does not follow
`globals()`, `exec`, or a name injected by a decorator, and it deliberately
treats every module-level assignment and import as available. The question it
asks is the narrowest one that catches this: *does this function use a bare
name that is neither its parameter, nor assigned in it, nor defined at module
level?*
python scripts/check_unresolved_names.py
python scripts/check_unresolved_names.py --selftest
"""
from __future__ import annotations
import argparse
import ast
import builtins
import pathlib
import sys
ROOT = pathlib.Path(__file__).resolve().parent.parent
#: ⛔ `scripts/` IS IN THE PERIMETER SINCE 2026-08-29, and leaving it out was
#: not a scoping decision - it was a hole this gate exists to close. On that
#: date `upstream_baseline.py:_per_file` was found returning `1 if morti else
#: 0` with `morti` assigned nowhere: a guaranteed NameError, sitting in the
#: repository, while this gate reported "none in 102 file(s)". Pointed at that
#: one file by hand it named the fault correctly, so the LOGIC was never
#: wrong; only the perimeter was.
#:
#: And the argument for scanning `scripts/` is STRONGER than for the package,
#: not weaker. The reason this class of defect survives is that a NameError
#: inside a function is invisible until someone calls it - and the package has
#: 529 unit tests calling into it, while these scripts have none. `_per_file`
#: is reached only by `--per-file`, on the async arm, forty minutes into a run
#: nobody makes twice.
#:
#: Measured before widening: 22 files, zero findings besides the real one - so
#: this costs no false positives to keep.
SCANNED = [ROOT / "src" / "invisible_playwright", ROOT / "scripts"]
sys.stdout.reconfigure(encoding="utf-8")
_FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef)
def _module_names(tree: ast.AST) -> set:
known = {n.name for n in ast.walk(tree)
if isinstance(n, _FUNCTIONS + (ast.ClassDef,))}
known |= {t.id for n in ast.walk(tree) if isinstance(n, ast.Assign)
for t in n.targets if isinstance(t, ast.Name)}
known |= {n.target.id for n in ast.walk(tree)
if isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name)}
known |= {a.asname or a.name.split(".")[0]
for n in ast.walk(tree) if isinstance(n, (ast.Import, ast.ImportFrom))
for a in n.names}
# ⛔ THE MODULE DUNDERS, which are not builtins and are not imports:
# Python puts them in the module namespace itself. They only became
# reachable when this gate started walking module-level functions, and
# `__file__` in a plain function is the commonest of them by far - it was
# the first false positive the widening produced.
known |= {"__file__", "__name__", "__doc__", "__package__", "__spec__",
"__loader__", "__builtins__", "__path__"}
return known | set(dir(builtins))
def _bound_in(fn: ast.AST) -> set:
"""Every name that exists inside this function by the time it runs.
⛔ Nested functions and lambdas contribute their PARAMETERS, because the
outer body legitimately refers to them; comprehension targets and `except
... as` names too. Leaving any of those out turns ordinary code into a
fault, and a check that cries wolf is switched off after the third time.
"""
args = fn.args
bound = {a.arg for a in list(args.args) + list(args.kwonlyargs)
+ list(getattr(args, "posonlyargs", []))}
if args.vararg:
bound.add(args.vararg.arg)
if args.kwarg:
bound.add(args.kwarg.arg)
for n in ast.walk(fn):
if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store):
bound.add(n.id)
elif isinstance(n, _FUNCTIONS + (ast.Lambda,)) and n is not fn:
inner = n.args
for a in (list(inner.args) + list(inner.kwonlyargs)
+ list(getattr(inner, "posonlyargs", []))):
bound.add(a.arg)
# ⛔ `*args` and `**kw` OF THE NESTED FUNCTION TOO. Leaving these
# out is not a small gap: the first run of this checker over the
# real package reported 10 faults and every one of them was this -
# `def patched(**kw)` inside a wrapper, which is the single most
# common shape in the file it was scanning. A checker that is
# wrong ten times out of ten teaches people to ignore it, and the
# two REAL defects it had just found would have been ignored with
# the rest.
if inner.vararg:
bound.add(inner.vararg.arg)
if inner.kwarg:
bound.add(inner.kwarg.arg)
if not isinstance(n, ast.Lambda):
bound.add(n.name)
elif isinstance(n, ast.comprehension):
for t in ast.walk(n.target):
if isinstance(t, ast.Name):
bound.add(t.id)
elif isinstance(n, ast.ExceptHandler) and n.name:
bound.add(n.name)
elif isinstance(n, ast.Global):
bound.update(n.names)
elif isinstance(n, ast.Nonlocal):
bound.update(n.names)
return bound
def unresolved(source: str, where: str = "<source>") -> list:
tree = ast.parse(source)
known = _module_names(tree)
out = []
def scan(fn, owner):
bound = _bound_in(fn)
for n in ast.walk(fn):
if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load):
if n.id not in bound and n.id not in known:
out.append((where, owner, fn.name, n.id, n.lineno))
for cls in [n for n in ast.walk(tree) if isinstance(n, ast.ClassDef)]:
for fn in [n for n in cls.body if isinstance(n, _FUNCTIONS)]:
scan(fn, cls.name)
# ⛔ MODULE-LEVEL FUNCTIONS TOO, and they were invisible until
# 2026-08-29. This gate was written against a file of dispatcher classes,
# so it walked classes and nothing else; a plain function was never looked
# at. It cost a real defect the day a refactor moved seventeen leaf helpers
# into two new modules with no classes at all: one of them used `json`
# without importing it, this gate reported "none in 103 files", and the
# failure surfaced as a NameError out of one test - which is the exact
# shape it exists to catch before a caller does.
for fn in [n for n in tree.body if isinstance(n, _FUNCTIONS)]:
scan(fn, "<module>")
return out
SELFTEST = [
("the defect itself: used, never taken",
"class A:\n def op(self, x):\n return self.go(frame_id)\n", 1),
("a parameter is not a fault",
"class A:\n def op(self, frame_id):\n return frame_id\n", 0),
("a keyword-only parameter is not a fault",
"class A:\n def op(self, *, frame_id=None):\n return frame_id\n", 0),
("something assigned in the body is not a fault",
"class A:\n def op(self):\n v = 1\n return v\n", 0),
("a module-level name is not a fault",
"H = 1\nclass A:\n def op(self):\n return H\n", 0),
("a MODULE-LEVEL FUNCTION using a name nobody imported",
"def helper(x):\n return json.dumps(x)\n", 1),
("the same module-level function with the import present",
"import json\ndef helper(x):\n return json.dumps(x)\n", 0),
("__file__ in a module-level function is not a fault",
"def where():\n return __file__\n", 0),
("an import is not a fault",
"import json\nclass A:\n def op(self):\n return json\n", 0),
("a builtin is not a fault",
"class A:\n def op(self):\n return len([])\n", 0),
("a nested function's parameter is not a fault",
"class A:\n def op(self):\n def run(p):\n return p\n"
" return run\n", 0),
("a comprehension target is not a fault",
"class A:\n def op(self):\n return [i for i in range(3)]\n", 0),
("an except-as name is not a fault",
"class A:\n def op(self):\n try:\n pass\n"
" except ValueError as e:\n return e\n", 0),
("two in one function are both reported",
"class A:\n def op(self):\n return (a_missing, b_missing)\n", 2),
# ⛔ The two below are the shape that produced 10 false alarms on the first
# real run. They are here so the next person who tightens `_bound_in` finds
# out immediately instead of from a wall of noise.
("a nested function's **kwargs is not a fault",
"class A:\n def op(self):\n def patched(**kw):\n"
" return kw\n return patched\n", 0),
("a lambda's *args is not a fault",
"class A:\n def op(self):\n return lambda *args: args\n", 0),
]
def selftest() -> int:
bad = 0
for name, source, expected in SELFTEST:
got = len(unresolved(source))
ok = got == expected
bad += 0 if ok else 1
print(" %-48s %s (%d, expected %d)"
% (name, "ok" if ok else "BROKEN", got, expected))
print("selftest: %d cases, %d broken" % (len(SELFTEST), bad))
return 1 if bad else 0
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--selftest", action="store_true")
p.add_argument("paths", nargs="*",
help="default: the package's own source, plus scripts/")
a = p.parse_args()
if a.selftest:
return selftest()
files = ([pathlib.Path(x) for x in a.paths]
or sorted(f for root in SCANNED for f in root.rglob("*.py")))
faults = []
for f in files:
try:
faults += unresolved(f.read_text(encoding="utf-8"), str(f))
except SyntaxError as bad:
print(" %s: cannot be parsed (%s)" % (f, bad))
return 2
for where, cls, fn, name, line in faults:
print(" %s :: %s.%s uses %r at line %d and never has it"
% (pathlib.Path(where).name, cls, fn, name, line))
if faults:
print("UNRESOLVED NAMES: %d. Each one is a NameError waiting for the "
"first caller of that method." % len(faults))
return 1
print("UNRESOLVED NAMES: none in %d file(s)." % len(files))
return 0
if __name__ == "__main__":
sys.exit(main())
-318
View File
@@ -1,318 +0,0 @@
"""Do the two servers receive the same thing, and answer the same thing?
⛔ THIS IS THE QUESTION THAT DECIDES WHETHER THE NODE DRIVER CAN BE DELETED, and
it is not the same question `judge_both_transports.py` answers. That one runs
tests and reports which arm goes red - a behavioural check, and a coarse one: a
field the client does not happen to read today is missing in complete silence,
and shows up as a bug months later in a code path nobody exercised. This one
compares the WIRE.
**What it compares, and why at this level.**
* **input**: every method the client SENDS, and the set of PARAMETER NAMES it
sends with each. Both servers must accept the same vocabulary. A method
present on one side and absent on the other is a hole; a method present on
both but reached with different fields means the client is being driven
differently, which makes the rest of the comparison meaningless.
* **output**: every object TYPE the server creates, and the set of INITIALIZER
FIELD NAMES for each; plus every EVENT name the server emits, per type. This
is the half that reading `_impl` cannot give you: it tells you which fields
are CONSUMED today, never which are SENT, and the difference is exactly the
set a future code path will want.
⛔ **FIELD NAMES, NOT VALUES.** guids are allocated by whoever allocates them,
ports are ephemeral, versions and build ids differ by construction. Comparing
values would drown the real differences in noise that is not a difference at
all. Where a VALUE matters it belongs in a test, not here.
⛔ **AND IT RUNS THE SAME SESSION TWICE, IN TWO SUBPROCESSES.** The transport is
chosen once, at import time, from the environment: two transports in one process
would mean one of the two arms was not the thing it claims to be.
python scripts/diff_protocol.py <firefox-binary>
python scripts/diff_protocol.py <firefox-binary> --keep (leave the traces)
"""
from __future__ import annotations
import argparse
import json
import os
import pathlib
import subprocess
import sys
import tempfile
ROOT = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "src"))
sys.stdout.reconfigure(encoding="utf-8")
#: Fields whose ABSENCE on one side is not a finding, because the two paths
#: legitimately disagree about them. Kept short and each one argued: a long
#: list here is how a comparison stops comparing.
EXPECTED_DIFFERENCES = {
# The driver reports the bundled Playwright's version string; we report the
# engine's. Neither is wrong and no client behaviour depends on the text.
("Playwright", "initializer", "preLaunchedBrowser"),
# ⛔ `previewUpdated` is a REAL gap, listed here because it is argued and
# not because it is small. The driver pushes a new preview string every
# time a handle's value changes, and `_js_handle.py` does listen for it -
# so on this server `repr(handle)` keeps the preview it was born with.
# That is the whole consequence: it reaches error messages and the REPL,
# never a page, never a decision, never a byte on the wire. Implementing it
# would mean re-serialising every handle after every evaluation, which is
# protocol traffic and parent-process work for a string a human reads.
# If it ever stops being cosmetic - a client that BRANCHES on the preview -
# this line is where to start.
("ElementHandle", "event", "previewUpdated"),
("JSHandle", "event", "previewUpdated"),
}
#: A checkout that still carries the Node driver, for the day this one does not.
#: Same contract and same reason as in `judge_both_transports.py`: a worktree,
#: not an installed release, because a published wrapper pins a published core
#: and a sealed engine and cannot drive a locally built binary.
#:
#: git worktree add /tmp/judge <the last commit that carried _driver/>
#: INVPW_DRIVER_TREE=/tmp/judge python scripts/diff_protocol.py <binary>
DRIVER_TREE_ENV = "INVPW_DRIVER_TREE"
def capture(binary: str, transport: str, out: pathlib.Path) -> None:
"""Run the scripted session under one transport, writing its trace."""
env = dict(os.environ)
env["INVPW_TRANSPORT"] = transport
env["INVPW_TRACE_OUT"] = str(out)
tree = os.environ.get(DRIVER_TREE_ENV)
if transport == "driver" and tree:
# ⛔ The driver comes from the older tree; the RECORDER does not. The
# capture script has to be this one, or the two traces are produced by
# two different instruments and every difference between them measures
# the instruments - which is the mistake this whole comparison exists
# to avoid.
src = str(pathlib.Path(tree) / "src")
env["PYTHONPATH"] = os.pathsep.join(
[src] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else []))
script = ROOT / "scripts" / "capture_protocol.py"
r = subprocess.run([sys.executable, str(script), binary, "-o", str(out)],
env=env, capture_output=True, text=True)
if r.returncode != 0 or not out.exists():
raise RuntimeError("the %s arm did not produce a trace:\n%s\n%s"
% (transport, r.stdout[-2000:], r.stderr[-2000:]))
def sent_vocabulary(trace: list) -> dict:
"""method -> the set of parameter names ever sent with it."""
out: dict = {}
for entry in trace:
if entry["dir"] != "send":
continue
message = entry["msg"]
method = message.get("method")
if not method:
continue
params = message.get("params") or {}
out.setdefault(method, set()).update(params.keys())
return out
def created_shapes(trace: list) -> dict:
"""type -> the set of initializer field names ever seen for it."""
out: dict = {}
for entry in trace:
if entry["dir"] != "recv":
continue
message = entry["msg"]
if message.get("method") != "__create__":
continue
params = message.get("params") or {}
kind = params.get("type")
if not kind:
continue
out.setdefault(kind, set()).update(
(params.get("initializer") or {}).keys())
return out
def events_by_owner(trace: list, shapes_of_guid: dict) -> dict:
"""type -> the set of event names the server emitted on objects of it."""
out: dict = {}
for entry in trace:
if entry["dir"] != "recv":
continue
message = entry["msg"]
method = message.get("method")
if not method or method.startswith("__"):
continue
kind = shapes_of_guid.get(message.get("guid"), "?")
out.setdefault(kind, set()).add(method)
return out
def parentage(trace: list, types: dict) -> dict:
"""child TYPE -> the set of parent TYPES it was ever created under.
⛔ A FOURTH DIMENSION, ADDED BECAUSE ITS ABSENCE LET A REAL DEFECT
THROUGH. This server created `ElementHandle` as a child of `Page`; the
driver creates it under `Frame`. Types matched, initializer fields matched,
events matched - and every call that reads a timeout off the handle's frame
died with `'Page' object has no attribute '_timeout'`, because
`_element_handle.py` learns its frame from the guid TREE and from nothing
else. Parentage is protocol, not bookkeeping.
"""
out: dict = {}
for entry in trace:
if entry["dir"] != "recv":
continue
message = entry["msg"]
if message.get("method") != "__create__":
continue
params = message.get("params") or {}
kind = params.get("type")
if not kind:
continue
out.setdefault(kind, set()).add(types.get(message.get("guid"), "root"))
return out
def disposed_types(trace: list, types: dict) -> dict:
"""type -> whether an object of it was ever disposed ("yes" or nothing).
⛔ A FIFTH DIMENSION, AND THE FOUR ABOVE ARE BLIND TO IT BY CONSTRUCTION:
`events_by_owner` skips every method starting with `__`, so `__dispose__`
was invisible to this comparison no matter how far the two servers drifted.
It is not bookkeeping either - the client ACTS on it, dropping the object
from its registry - so a server that never disposes anything grows the
client's registry for the life of the browser, and a server that disposes
something the client still holds hands back a dead reference.
It was added on 2026-08-28 to answer a question the PARITY verdict could
not: this server never disposed a closed page, and the count of live
objects grew by one per page (9 at page 0, 508 at page 499). Whether that
is a defect or a difference depends entirely on what the driver does, and
nothing here could see it.
The value is a one-element set rather than a bool so `report` can compare
it like every other dimension.
"""
out: dict = {}
for entry in trace:
if entry["dir"] != "recv":
continue
message = entry["msg"]
if message.get("method") != "__dispose__":
continue
kind = types.get(message.get("guid"))
if kind:
out.setdefault(kind, set()).add("disposed")
return out
def guid_types(trace: list) -> dict:
"""guid -> its type, so an event can be attributed to a KIND of object."""
out: dict = {}
for entry in trace:
if entry["dir"] != "recv":
continue
message = entry["msg"]
if message.get("method") != "__create__":
continue
params = message.get("params") or {}
if params.get("guid"):
out[params["guid"]] = params.get("type")
return out
def report(label: str, ours: dict, theirs: dict, kind: str) -> list:
"""Differences in one dimension, as lines. Empty means parity."""
faults = []
def kept(name, fields):
"""⛔ The argued differences are filtered HERE TOO, and they were not.
A field can be missing two ways: the key exists on both sides and one
set is short, or the key is absent entirely. The first version only
filtered the first, so an event type that appears on the driver and
nowhere on ours stayed red forever no matter what was written about
it - and a gate with a permanent red is a gate people stop reading."""
return sorted(f for f in fields
if (name, kind, f) not in EXPECTED_DIFFERENCES)
for name in sorted(set(theirs) - set(ours)):
rest = kept(name, theirs[name])
if rest:
faults.append("%s %r reaches the DRIVER and not us: %s"
% (label, name, rest))
for name in sorted(set(ours) - set(theirs)):
rest = kept(name, ours[name])
if rest:
faults.append("%s %r reaches US and not the driver: %s"
% (label, name, rest))
for name in sorted(set(ours) & set(theirs)):
missing = theirs[name] - ours[name]
extra = ours[name] - theirs[name]
missing = {f for f in missing
if (name, kind, f) not in EXPECTED_DIFFERENCES}
extra = {f for f in extra
if (name, kind, f) not in EXPECTED_DIFFERENCES}
if missing:
faults.append("%s %r: the driver carries %s and we do not"
% (label, name, sorted(missing)))
if extra:
faults.append("%s %r: we carry %s and the driver does not"
% (label, name, sorted(extra)))
return faults
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("binary")
p.add_argument("--keep", action="store_true",
help="leave the two traces on disk for inspection")
a = p.parse_args()
work = pathlib.Path(tempfile.mkdtemp(prefix="protocol_diff_"))
driver_trace = work / "driver.json"
ours_trace = work / "juggler.json"
print("recording the DRIVER arm ...", flush=True)
capture(a.binary, "driver", driver_trace)
print("recording the PYTHON arm ...", flush=True)
capture(a.binary, "juggler", ours_trace)
driver = json.loads(driver_trace.read_text(encoding="utf-8"))
ours = json.loads(ours_trace.read_text(encoding="utf-8"))
print()
print(" driver: %d messages python: %d messages"
% (len(driver), len(ours)))
faults = []
faults += report("method", sent_vocabulary(ours), sent_vocabulary(driver),
"params")
faults += report("object", created_shapes(ours), created_shapes(driver),
"initializer")
faults += report("events on", events_by_owner(ours, guid_types(ours)),
events_by_owner(driver, guid_types(driver)), "event")
faults += report("parent of", parentage(ours, guid_types(ours)),
parentage(driver, guid_types(driver)), "parent")
faults += report("disposal of", disposed_types(ours, guid_types(ours)),
disposed_types(driver, guid_types(driver)), "dispose")
print()
for line in faults:
print(" " + line)
if a.keep or faults:
print()
print(" traces: %s" % work)
if faults:
print("PROTOCOL DIFF: %d difference(s). The Node driver cannot be "
"deleted while any of these stand, or a caller who reaches one "
"gets silence instead of a browser." % len(faults))
return 1
print("PROTOCOL DIFF: PARITY - same methods with the same parameters in, "
"same object types with the same initializer fields, the same "
"events, the same parentage and the same disposals out.")
return 0
if __name__ == "__main__":
sys.exit(main())
+115
View File
@@ -0,0 +1,115 @@
"""HUNT ONLY (branch hunt/page-bytes-reference, never merged): record the reference of what a page reads, per operating system.
python scripts/hunt_page_bytes_reference.py --binary "$FF" --out DIR [--launches 2]
It does what test 3 of tests/test_software_compositing_is_declared_e2e.py does (the same launch, the same page, the same probe
tests/page_bytes_probe.js), `--launches` times, in the engine and with the core this checkout installed, and instead of comparing with
tests/data/page_bytes_<os>.json it WRITES that file:
* every key whose entry (tests/_page_bytes.entry_of: the string, or hash and length; for a PNG key the length and the decoded pixels)
is the same in every launch goes to the reference;
* every key that is not (an unstable key) is listed apart, with its entries, and left out of the reference: a reference holds nothing
that changes by itself.
Out, in DIR: page_bytes_<os>.json (the reference, in the form the test reads: copy it to tests/data/), unstable.json, launch-<n>.json.gz
(the raw probe values of each launch) and summary.txt. The log gets the reference between RECORD-BEGIN <os> and RECORD-END.
"""
from __future__ import annotations
import argparse
import gzip
import json
import os
import re
import sys
from importlib import metadata
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
import _page_bytes as pb # noqa: E402
import test_software_compositing_is_declared_e2e as t # noqa: E402 (LAUNCH, the page server, OS_NAME: what test 3 uses)
def one_launch(binary: str) -> dict:
from invisible_playwright import InvisiblePlaywright
expression = (ROOT / "tests" / "page_bytes_probe.js").read_text(encoding="utf-8")
server, url = t._a_page_server("<!doctype html><meta charset=utf-8><title>probe</title><body></body>")
try:
with InvisiblePlaywright(binary_path=binary, **t.LAUNCH) as browser:
page = browser.new_page()
page.goto(url, wait_until="load", timeout=60000)
return page.evaluate(expression)
finally:
server.shutdown()
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--binary", default=os.environ.get("INVPW_BINARY_PATH", ""))
ap.add_argument("--out", type=Path, required=True)
ap.add_argument("--launches", type=int, default=2)
args = ap.parse_args()
if not args.binary:
ap.error("--binary (or INVPW_BINARY_PATH)")
args.out.mkdir(parents=True, exist_ok=True)
launches = []
for n in range(1, args.launches + 1):
data = one_launch(args.binary)
with gzip.open(args.out / ("launch-%d.json.gz" % n), "wt", encoding="utf-8") as f:
json.dump(data, f)
launches.append(data)
print("launch %d: %d keys, %d scene error(s)%s" % (n, len(data), len([k for k in data if k.endswith(".error")]),
(": " + ", ".join("%s=%s" % (k, data[k].get("s")) for k in sorted(data) if k.endswith(".error")))
if any(k.endswith(".error") for k in data) else ""))
sys.stdout.flush()
keys = sorted(set().union(*[set(d) for d in launches]))
stable, pngs, unstable = {}, {}, {}
for key in keys:
if any(key not in d for d in launches):
unstable[key] = ["missing in launch %d" % (i + 1) for i, d in enumerate(launches) if key not in d]
continue
entries = [pb.entry_of(key, d[key]) for d in launches]
if any(e != entries[0] for e in entries) or "undecodable" in entries[0] or (pb.is_png_key(key) and "sha256" not in entries[0]):
unstable[key] = entries
continue
(pngs if pb.is_png_key(key) else stable)[key] = entries[0]
engine = re.search(r"firefox-\d+_[\d.]+_\d+", args.binary.replace("\\", "/"))
reference = {
"os": t.OS_NAME,
"source": ("GitHub Actions run %s (workflow page-bytes-reference-hunt, runner image %s %s), wrapper commit %s, invisible-core %s, engine %s, seed %d, "
"locale %s, timezone %s, headless=True; %d launches, every key below is equal in all of them. `pngs`: the PNG keys, compared on their "
"length and decoded pixels because every PNG carries a per-launch chunk."
% (os.environ.get("GITHUB_RUN_ID", "?"), os.environ.get("ImageOS", "?"), os.environ.get("ImageVersion", "?"),
os.environ.get("GITHUB_SHA", "?")[:10], metadata.version("invisible-core"), engine.group(0) if engine else "?",
t.LAUNCH["seed"], t.LAUNCH["locale"], t.LAUNCH["timezone"], args.launches)),
"keys": stable,
"pngs": pngs,
}
path = args.out / ("page_bytes_%s.json" % t.OS_NAME)
path.write_text(json.dumps(reference, indent=1) + "\n", encoding="utf-8", newline="\n")
(args.out / "unstable.json").write_text(json.dumps(unstable, indent=1) + "\n", encoding="utf-8", newline="\n")
lines = ["page bytes on %s, %d launches, invisible-core %s: %d keys read, %d stable (%d of them PNG), %d UNSTABLE"
% (t.OS_NAME, args.launches, metadata.version("invisible-core"), len(keys), len(stable) + len(pngs), len(pngs), len(unstable))]
lines += [" unstable: %s %s" % (k, json.dumps(v)[:300]) for k, v in unstable.items()]
lines += [" scene error: %s = %s" % (k, stable[k].get("s")) for k in sorted(stable) if k.endswith(".error")]
summary = "\n".join(lines)
(args.out / "summary.txt").write_text(summary + "\n", encoding="utf-8", newline="\n")
print(summary)
print("RECORD-BEGIN %s" % t.OS_NAME)
print(json.dumps({"keys": stable, "pngs": pngs}, sort_keys=True))
print("RECORD-END")
if os.environ.get("GITHUB_STEP_SUMMARY"):
with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as f:
f.write("### Page bytes, %s\n\n```\n%s\n```\n" % (t.OS_NAME, summary))
return 0
if __name__ == "__main__":
sys.exit(main())
-195
View File
@@ -1,195 +0,0 @@
"""Run the same e2e through BOTH transports and compare, test by test.
⛔ THIS IS THE JUDGEMENT ITEM 8 WAITS FOR. The Node driver and the Python
server answer the same protocol, so the only honest way to know the second one
is correct is to run the same session through both and compare the results
name by name. Deleting the driver before this has run leaves the new path with
nothing to be measured against - a build that agrees with itself.
⛔ AND A DIFFERENCE IS NOT AUTOMATICALLY OURS. In two days this comparison has
already answered in both directions: `go_back` fails identically on both arms,
so it is the engine ([B185]); an unanswered dialog failed only on ours, so it
was ours. The table below keeps them apart instead of counting failures.
python scripts/judge_both_transports.py <firefox-binary>
python scripts/judge_both_transports.py <binary> -k juggler # a subset
⛔ THE MACHINE MUST BE QUIET. Both arms launch real browsers, and this project
has three recorded cases of measuring under load and reading the noise as a
product defect. The script refuses to start if a firefox is already alive.
⛔ AND THE ARMS RUN INTERLEAVED PER FILE, never all-of-A then all-of-B. Machine
load and disk cache drift over minutes; running one arm to completion first
puts every one of its tests in a different window from the other's, which turns
"this arm is worse" and "that minute was worse" into the same measurement.
"""
from __future__ import annotations
import argparse
import pathlib
import re
import subprocess
import sys
ROOT = pathlib.Path(__file__).resolve().parent.parent
#: The files worth running on both. ⛔ NOT the whole suite: most of it never
#: touches a transport, so running it twice would double the time and add no
#: information. These are the ones that drive a browser through the seam.
FILES = [
"tests/test_juggler_transport.py",
"tests/test_hidden_desktop.py",
"tests/test_new_page_defaults.py",
"tests/test_cross_origin_iframe.py",
"tests/test_file_chooser.py",
]
ESITO = re.compile(r"^(tests[^\s:]+)::(\S+)\s+(PASSED|FAILED|ERROR|XFAIL|XPASS|SKIPPED)",
re.M)
def quiet_machine() -> int:
r = subprocess.run(
["powershell", "-NoProfile", "-Command",
"(Get-Process firefox -ErrorAction SilentlyContinue | Measure-Object).Count"],
capture_output=True, text=True)
try:
return int((r.stdout or "0").strip() or 0)
except ValueError:
return -1
#: A checkout that still carries the Node driver, for the day this one does not.
#:
#: ⛔ THIS GATE EXISTS ONLY WHILE THERE ARE TWO ARMS, and the driver is on its
#: way out of the tree. When it goes, the second arm comes from a git worktree
#: at the last commit that carried it:
#:
#: git worktree add /tmp/judge <that commit>
#: INVPW_DRIVER_TREE=/tmp/judge python scripts/judge_both_transports.py <bin>
#:
#: A worktree rather than an installed release, because a published wrapper
#: pins a published core and a sealed engine and therefore cannot drive a
#: locally built binary - which is the only kind worth judging.
DRIVER_TREE_ENV = "INVPW_DRIVER_TREE"
def run_one(transport: str, binary: str, path: str, extra: list) -> dict:
import os
env = dict(os.environ)
env["INVPW_TRANSPORT"] = transport
env["INVPW_BINARY_PATH"] = binary
tree = os.environ.get(DRIVER_TREE_ENV)
if transport == "driver" and tree:
# ⛔ PREPENDED, so the older tree's package wins the import. The TESTS
# still come from this checkout: what is being borrowed is the driver,
# not the suite, and running the old suite would compare two different
# sets of assertions and call it a transport difference.
src = str(pathlib.Path(tree) / "src")
env["PYTHONPATH"] = os.pathsep.join(
[src] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else []))
r = subprocess.run(
[sys.executable, "-m", "pytest", path, "-o", "addopts=", "-v",
"-p", "no:cacheprovider"] + extra,
cwd=ROOT, env=env, capture_output=True, text=True, timeout=3600)
return {name: verdict
for _, name, verdict in ESITO.findall(r.stdout + r.stderr)}
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("binary")
p.add_argument("-k", dest="selection", default=None)
p.add_argument("--allow-busy", action="store_true",
help="run even with a browser already alive. ⛔ The result "
"is then not a measurement, and the report says so.")
a = p.parse_args()
alive = quiet_machine()
if alive and not a.allow_busy:
print("REFUSING: %d firefox processes are already alive. A run under "
"load is not a measurement - this project has three recorded "
"cases of reading that noise as a product defect. Close them, or "
"pass --allow-busy and read the result as indicative." % alive)
return 2
if alive:
print("WARNING: %d firefox alive, the result is INDICATIVE" % alive)
extra = ["-k", a.selection] if a.selection else []
driver, juggler = {}, {}
for path in FILES:
if not (ROOT / path).exists():
print(" (skipped, absent: %s)" % path)
continue
print("running %s ..." % path, flush=True)
# ⛔ Interleaved per file: see the module docstring.
driver.update(run_one("driver", a.binary, path, extra))
juggler.update(run_one("juggler", a.binary, path, extra))
names = sorted(set(driver) | set(juggler))
ok = both_fail = only_ours = only_theirs = not_run = 0
rows = []
for name in names:
d = driver.get(name, "ABSENT")
j = juggler.get(name, "ABSENT")
good = ("PASSED", "XFAIL", "SKIPPED")
# ⛔ A TEST THE OTHER ARM NEVER RAN IS NOT A TEST THE OTHER ARM
# FAILED, and folding the two was making this gate lie in the
# comfortable direction. The driver arm imports an OLD `src/`, so any
# test file naming something added since that commit fails to COLLECT
# there and every test in it comes back ABSENT. Counted as "only the
# driver fails", they printed under "ours is BETTER here" - measured
# 2026-08-28 at 32 of them, essentially all of that kind. The number
# grows on its own as this tree moves, which is the property that
# turns a gate into decoration.
if "ABSENT" in (d, j) and not (d in good and j in good):
not_run += 1
rows.append(("NOT RUN", name, d, j))
elif d in good and j in good:
ok += 1
elif d not in good and j not in good:
both_fail += 1
rows.append(("ENGINE?", name, d, j))
elif d in good:
only_ours += 1
rows.append(("OURS", name, d, j))
else:
only_theirs += 1
rows.append(("DRIVER", name, d, j))
print()
print("=" * 78)
print("%-8s %-46s %-10s %s" % ("verdict", "test", "driver", "juggler"))
print("-" * 78)
for kind, name, d, j in rows:
print("%-8s %-46s %-10s %s" % (kind, name[:46], d, j))
print("-" * 78)
print("both green %d" % ok)
print("BOTH fail -> the ENGINE %d" % both_fail)
print("only OURS fails %d <- the ones that are ours to fix"
% only_ours)
print("only the DRIVER fails %d <- ours is BETTER here, verify why"
% only_theirs)
print("never ran on one arm %d <- NOT a comparison: the old arm "
"could not collect these" % not_run)
if not_run:
print()
print(" WARNING: %d of the rows above were never compared at all. The driver "
"arm's `src/` is a worktree that ages: a test naming anything "
"added since it was cut fails to collect there. When this number "
"approaches the total, this gate has stopped answering its own "
"question and the worktree needs re-cutting." % not_run)
print()
if only_ours:
print("VERDICT: not ready to delete the driver. %d tests pass through "
"it and fail through us." % only_ours)
return 1
print("VERDICT: no test passes on the driver and fails on us.")
if both_fail:
print(" (%d fail on BOTH: engine defects, not a reason to wait)"
% both_fail)
return 0
if __name__ == "__main__":
sys.exit(main())
+1 -1
View File
@@ -7,7 +7,7 @@ against anything of ours: its `conftest.py` imports the real `playwright`
package, so it has only ever measured Microsoft's client.
The plan it serves: replacing the channel between our client and our server
removes the boundary `diff_protocol.py` compares across, so the judgement has to
removes the boundary the old protocol comparison compared across, so the judgement has to
move up a level, from the PROTOCOL to the CONTRACT. This suite is that judge -
but only if we know, before touching anything, which of those 2173 pass TODAY.
A baseline taken afterwards proves nothing: every failure would be arguable.
+6 -6
View File
@@ -52,14 +52,14 @@ did so on evidence rather than on the code looking finished:
regenerating them. `injected.js` (the selector engines, actionability and
`expect` that run in the page), `keylayout.py` (both in `invisible_core.juggler`
since 0.30.0, with their extractors in the core's `scripts/`), and the four rules
`prefs_byte_parity.py` compares our `user.js` writer against - now frozen in
`tests/gates/driver_prefs_rules.json` with the sha of the bundle and of the
exact window they came from.
- ⛔ And the second arm. `judge_both_transports.py` and `diff_protocol.py` exist
only while there are two implementations to compare. To get one back:
the `user.js` writer was compared against (the comparison script and the frozen
rules file were later deleted; they are in git history).
- ⛔ And the second arm. A comparison between the two transports only exists
while there are two implementations to compare, and the scripts that did it
were deleted with the driver arm. To get one back:
git worktree add /tmp/judge <the last commit that carried _driver/>
INVPW_DRIVER_TREE=/tmp/judge python scripts/judge_both_transports.py <bin>
INVPW_DRIVER_TREE=/tmp/judge python scripts/capture_protocol.py <bin>
A worktree rather than an installed release, because a published wrapper pins
a published core and a sealed engine and therefore cannot drive a locally
@@ -0,0 +1,88 @@
"""`expose_binding` / `expose_function`: the script a page runs, and the way a call is read and answered.
THE RULE: THE PAGE SEES `foo` AND NOTHING ELSE. A page can list the names on its window, so a transport left there ("a binding
function", a controller) is the driver's signature. Nothing is left:
* One engine binding PER EXPOSED NAME (`Browser.addBinding` for a context, `Page.addBinding` for a page), under a native name chosen
for the session. The engine puts the native function on the window of every document of the page or context, present and future,
in every process, BEFORE any script of the page, and then runs the script below.
* The script takes the native function off the window at once and keeps it in a closure; defines `foo` (an ordinary function whose
source says nothing of what it is for); and hands the engine, through the native function, the function that answers a call
(the engine keeps it as an object of that context and reports its id: `payload.bindingEnd`).
* A call travels as a JSON string through the native function; the answer is `Runtime.callFunction` on the kept function.
LIMIT, SAID HERE. Arguments and results cross as JSON: `undefined`, functions and `NaN` arrive as `null`, and a `Date` as its ISO
string. A caller who needs one passes it as a string. Workers do not get the function (the engine installs bindings in the frames
of a page, as Playwright's does).
"""
from __future__ import annotations
import functools
import json
def install_script(native: str, name: str) -> str:
"""Run by the engine in each document, after it exports the native function `native` on the window."""
return (
"(() => {"
" const send = globalThis[%(native)s];"
" try { delete globalThis[%(native)s]; } catch (e) {}"
" if (typeof send !== 'function') return;"
" const text = JSON.stringify, waiting = new Map();"
" let last = 0;"
" const ask = (name, args) => new Promise((resolve, reject) => {"
" const id = ++last; waiting.set(id, [resolve, reject]);"
" try { send(text({ name, seq: id, args })); } catch (e) { waiting.delete(id); reject(e); } });"
" const f = { [%(name)s]: function (...args) { return ask(%(name)s, args); } }[%(name)s];"
" Object.defineProperty(globalThis, %(name)s,"
" { value: f, writable: true, configurable: true, enumerable: true });"
" send(function (id, ok, value) {"
" const w = waiting.get(id); if (!w) return; waiting.delete(id);"
" if (ok) w[0](value); else w[1](new Error(value)); });"
" })()") % {"native": json.dumps(native), "name": json.dumps(name)}
def remove_script(native: str, name: str) -> str:
"""The same binding again, as the engine runs the last one it was given for a native name: it takes the native function
off the window and the exposed function with it. A document that exists loses `foo`; one to come never gets it."""
return ("(() => { try { delete globalThis[%s]; } catch (e) {}"
" try { delete globalThis[%s]; } catch (e) {} })()") % (json.dumps(native), json.dumps(name))
#: `Runtime.callFunction` with the kept function as the first argument.
DELIVER = "(end, seq, ok, value) => end(seq, ok, value)"
def read_call(payload) -> tuple:
"""`(name, seq, args)` of a `Page.bindingCalled` payload, or `None` if it is not a call."""
try:
data = json.loads(payload) if isinstance(payload, str) else payload
return str(data["name"]), int(data["seq"]), list(data.get("args") or [])
except (TypeError, ValueError, KeyError):
return None
@functools.lru_cache(maxsize=16)
def engine_supports(engine_dir: str) -> bool:
"""Whether the engine in `engine_dir` has `Page.addBinding` and the binding that hands its end over.
Read from the engine's own files (the schema of its protocol, and its Runtime), so an engine without them is known BEFORE a
function is exposed: there is no fallback to a name on the window, and a clear refusal is the answer. An engine that cannot
be read is treated as one that cannot."""
if not engine_dir:
return False
try:
import os
from invisible_core.juggler._gen_protocol import protocol_source
_label, text = protocol_source(engine_dir)
if text.count("'addBinding'") < 2:
return False
omni = os.path.join(engine_dir, "omni.ja")
if os.path.isfile(omni):
from invisible_core.jar import open_jar
jar = open_jar(omni)
return b"bindingEnd" in jar.read("modules/juggler/content/Runtime.js")
return True
except BaseException:
return False
@@ -0,0 +1,126 @@
"""The one way this package starts a thread from a place that must not wait for it.
`Thread.start` does not return until the new thread is running (`self._started.wait()`), and on Windows under load that wait is
milliseconds long. Two places in the package cannot afford it: the engine connection's reader (an event is measured late by every
millisecond the reader is late) and the user's event loop (`InProcessTransport.connect`: four worker starts held the loop ~200 ms per
launch with four browsers in one process). Both hand the thread to `ThreadStarter`.
"""
from __future__ import annotations
import _thread as _raw_thread
import queue
import threading
from typing import Any, Callable, Optional
class ThreadStarter:
"""The ONE long-lived thread that starts the other threads it is handed.
⛔ NO `Thread.start` ON THE CALLER, AND THAT INCLUDES BUILDING THE STARTER. `start` and `start_built` only queue (a `Thread` that is
only BUILT waits for nothing); this thread starts what is queued. The starter's own thread is begun with `_thread.start_new_thread`
running `Thread.start`: the OS makes a thread and the caller returns at once, and the wait for the starter to run happens on that
raw thread, not on the caller. The starter is still a `threading.Thread` named `invpw-thread-starter` (it is alive a moment after
the constructor returns, not before).
It starts threads and does not run the work itself, on purpose: an adoption waits for the engine as long as the engine takes (a popup
whose destination never answers is waited for without a limit), and a worker that ran it would hold every later adoption behind it,
`new_page()` included. Each piece of work keeps the thread of its own and the name it always had.
"""
#: Every starter built and not yet ended (from the constructor, which returns before its thread runs, to the end of that thread).
#: Without it a starter whose thread has not begun yet is in no `threading.enumerate()` and nobody can count it: the census of
#: tests/_browser_census.py missed the leaked starters on a machine where the raw thread was late to run.
_open: "set" = set()
_open_lock = threading.Lock()
@classmethod
def open_starters(cls) -> list:
with cls._open_lock:
return list(cls._open)
def __init__(self, on_error: Callable[[str], None]) -> None:
with ThreadStarter._open_lock:
ThreadStarter._open.add(self)
self._queue: "queue.SimpleQueue" = queue.SimpleQueue()
self._on_error = on_error
self._stopped = False
self._thread = threading.Thread(target=self._run, daemon=True, name="invpw-thread-starter")
_raw_thread.start_new_thread(self._begin, ())
def _begin(self) -> None:
try:
self._thread.start()
except BaseException as failure:
self._ended()
self._report("%s could not be started: %s" % (self._thread.name, failure))
def _ended(self) -> None:
with ThreadStarter._open_lock:
ThreadStarter._open.discard(self)
def start(self, **thread_arguments: Any) -> None:
"""Called from any thread, the reader's and the loop's included: builds a daemon thread and queues it. Never waits."""
if self._stopped:
return
self._queue.put((threading.Thread(daemon=True, **thread_arguments), None))
def start_built(self, thread: threading.Thread, on_failure: Optional[Callable[[str], None]] = None) -> None:
"""Queue a thread the caller built (its name, its daemon flag, its target). Never waits.
`on_failure(why)` runs on the starter if this thread cannot be started, besides the starter's own report."""
if self._stopped:
return
self._queue.put((thread, on_failure))
def stop(self) -> None:
self._stopped = True
self._queue.put(None)
def _report(self, why: str) -> None:
try:
self._on_error(why)
except Exception:
pass
def _run(self) -> None:
try:
self._loop()
finally:
self._ended()
def _loop(self) -> None:
while True:
item = self._queue.get()
if item is None:
return
thread, on_failure = item
try:
thread.start()
except Exception as failure:
why = "%s could not be started: %s" % (thread.name, failure)
self._report(why)
if on_failure is not None:
try:
on_failure(why)
except Exception:
pass
class ThreadStarterLease:
"""One browser's use of the connection's starter: `start` while the browser's connection lives, nothing after it.
The starter is the SERVER's (one thread per connection, however many browsers it launches, `Server.thread_starter`) and ends with
the server. A browser's connection ends earlier than that: from then on a thread its events ask for must not start, which is
what `stop` on the browser's own starter used to give. The starter is asked for on the first `start`, so a browser that never
needs a thread makes none."""
def __init__(self, get_starter: Callable[[], ThreadStarter]) -> None:
self._get_starter = get_starter
self._stopped = False
def start(self, **thread_arguments: Any) -> None:
if not self._stopped:
self._get_starter().start(**thread_arguments)
def stop(self) -> None:
self._stopped = True
@@ -39,6 +39,7 @@ import time
from typing import Any, Callable, Dict, List, Optional
from . import perimeter, variants
from ._threads import ThreadStarter
# One class for a target that is gone, raised here for a disposed object and
# by the connection for a closed pipe. Defined there, the lower layer.
from invisible_core.juggler.connection import TargetClosedError # noqa: F401 - re-exported on purpose
@@ -274,8 +275,30 @@ class Server:
self._on_shutdown: list = []
#: What `shutdown` runs after every hook. See `after_shutdown`.
self._after_shutdown: list = []
self._starter: Optional[ThreadStarter] = None
self._starter_lock = threading.Lock()
self._is_shut_down = False
#: Why a thread the starter was handed could not be started (the last few).
self.start_errors: list = []
# ── plumbing ────────────────────────────────────────────────────────────
@property
def thread_starter(self) -> ThreadStarter:
"""The ONE thread that starts threads for this connection: the transport's workers and every browser's reader hand theirs to it.
Built on first use, ended by `shutdown`. Served by several clients (`remote._SharedServer`) it is the same one: the server
is the connection's owner there too, and its browser's contexts come and go under it."""
with self._starter_lock:
if self._starter is None:
self._starter = ThreadStarter(self._start_failed)
if self._is_shut_down:
self._starter.stop()
return self._starter
def _start_failed(self, why: str) -> None:
if len(self.start_errors) < 32:
self.start_errors.append(why)
def attach(self, transport: Any) -> None:
self._transport = transport
@@ -436,6 +459,11 @@ class Server:
except Exception:
pass
self._after_shutdown.clear()
with self._starter_lock:
self._is_shut_down = True
starter = self._starter
if starter is not None:
starter.stop()
# ── the entry point ─────────────────────────────────────────────────────
def handle(self, message: Dict) -> Any:
@@ -169,13 +169,6 @@ FIXED_AT_BUILD = {
#: Our debt, plainly. Nothing external blocks these: they are not written yet.
#: This set is the honest list of what "100% compatible" does not cover today.
NOT_WIRED_YET = {
"exposeBinding",
# ⛔ `reject` shares its handler with `resolve`, and that is how it stayed
# invisible: the first scan keyed the method table by python name, so the
# second operation routed to `op_binding_reply` overwrote the first. Two
# operations, one handler, one of them unaccounted for.
"reject",
"resolve",
"setExtraHTTPHeaders",
}
+244 -96
View File
@@ -36,6 +36,7 @@ import pathlib
import queue
import sys
import tempfile
import secrets
import threading
import collections
import time
@@ -46,7 +47,8 @@ from invisible_core.juggler import PageActs, popup_number
from invisible_core.juggler import connection as juggler
from invisible_core.juggler.actions import Actions
from invisible_core.juggler.deadline import Deadline
from . import dialogs
from . import _bindings, dialogs
from ._threads import ThreadStarterLease
from .pointer import Pointer
from .dispatcher import (Dispatcher, ExpectNotMet, ProtocolException,
Server, current_call)
@@ -547,6 +549,12 @@ def _run_callers_code(injected: InjectedScript, frame_id: str, params: Dict,
return remote
def _round_px(value: float) -> int:
"""To the nearest whole pixel, halves up (Python's `round` goes to even: 0.5 -> 0, 1.5 -> 2)."""
import math
return int(math.floor(value + 0.5))
class ElementHandleDispatcher(Dispatcher):
TYPE = "ElementHandle"
METHODS = {
@@ -560,6 +568,7 @@ class ElementHandleDispatcher(Dispatcher):
"inputValue": "op_input_value",
"getAttribute": "op_get_attribute",
"scrollIntoViewIfNeeded": "op_scroll_into_view",
"screenshot": "op_screenshot",
"ownerFrame": "op_owner_frame",
"contentFrame": "op_content_frame",
"getProperty": "op_get_property",
@@ -799,6 +808,44 @@ class ElementHandleDispatcher(Dispatcher):
params.get("rect"))
return None
def op_screenshot(self, params: Dict) -> Any:
"""A picture of this element: scroll it into view, take its box, and
ask the page's own screenshot for exactly that rectangle.
⛔ THE BOX IS IN THE MAIN FRAME'S VIEWPORT, AND THE ENGINE'S CLIP IS IN
DOCUMENT COORDINATES. `Page.getContentQuads` answers in the main frame's
space whatever frame the element is in (it carries a node up every
`<iframe>`, across processes), so the same box is right for an element
of the page, of a frame of another site and of a frame nested in it.
What is missing to reach the document is the main frame's scroll, read
after the element has been scrolled in. The screenshot itself is the
page's (`PageDispatcher.op_screenshot`): a second path would be a second
place for the type, the quality and the scale to disagree.
The rectangle is rounded to whole pixels outward-stable, the way
Playwright's screenshotter does: the left and top edges to the nearest
pixel, the size from the rounded right and bottom edges.
"""
# An element with no layout object (display: none, detached) cannot be scrolled to: the engine says so
# with an exception of its own. For the caller that is the same answer as an empty box.
try:
self.injected.scroll_into_view(self.frame.frame_id, self.object_id, None)
box = self.injected.bounding_box(self.frame.frame_id, self.object_id)
except Exception:
box = None
if not box or box["width"] <= 0 or box["height"] <= 0:
raise ValueError("Element is not visible")
page = self.page
scroll = page.injected.evaluate(
page.frame.frame_id, "({x: window.scrollX, y: window.scrollY})") or {"x": 0, "y": 0}
left = _round_px(box["x"] + scroll["x"])
top = _round_px(box["y"] + scroll["y"])
right = _round_px(box["x"] + scroll["x"] + box["width"])
bottom = _round_px(box["y"] + scroll["y"] + box["height"])
clip = {"x": left, "y": top,
"width": max(right - left, 1), "height": max(bottom - top, 1)}
return page.op_screenshot(dict(params, clip=clip))
def op_owner_frame(self, params: Dict) -> Any:
return {"frame": self.frame.channel}
@@ -1058,6 +1105,9 @@ class FrameDispatcher(Dispatcher):
#: The load states the client has been told this frame has (the initializer's, then each `loadstate`): what the hand-over of the
#: page from its buffer to its dispatcher compares the lifecycle's states with (`PageDispatcher._reconcile_frame`).
self.told_states = set(load_states or ["commit"])
#: The address the client has been TOLD (the initializer's, then each `navigated` once it has gone up). `url`
#: is set a moment before the event is sent; a BindingCall waits for this one (`_announce_binding`).
self.committed_url = url
#: Same reason, and both navigation events report it: a same-document
#: navigation carries no name, so it has to repeat the one the frame
#: already has rather than blank it.
@@ -2684,6 +2734,48 @@ def _target_is_gone(error: BaseException) -> bool:
return True
text = str(error).lower()
return "cannot find session" in text or "target closed" in text or "session closed" in text
class BindingCallDispatcher(Dispatcher):
"""One call of an exposed function, waiting for the client's answer.
The client runs the Python function and sends `resolve` or `reject`; the answer goes back into the promise the page is
holding, in the context the call came from (`controller.deliver`, see `_bindings`)."""
TYPE = "BindingCall"
METHODS = {"resolve": "op_resolve", "reject": "op_reject"}
def __init__(self, server, page: "PageDispatcher", frame: "FrameDispatcher", context_id: str, native: str,
name: str, seq: int, args: List[Any]) -> None:
self.page = page
self.context_id = context_id
self.native = native
self.seq = seq
super().__init__(server, page, {
"frame": frame.channel, "name": name,
"args": [_serialize(a) for a in args]})
@staticmethod
def _deliver(page: "PageDispatcher", context_id: str, native: str, seq: int, ok: bool, value: Any) -> None:
end = page._binding_ends.get((context_id, native))
if end is None:
return # the document left (or never handed its end over): nobody is waiting
try:
page.injected.call_raw(context_id, _bindings.DELIVER,
[{"objectId": end}, {"value": seq}, {"value": ok}, {"value": value}],
by_value=True, timeout=10.0)
except Exception:
pass # the document left: nobody is waiting for the answer
def op_resolve(self, params: Dict) -> Any:
self._deliver(self.page, self.context_id, self.native, self.seq, True, _deserialize(params.get("result")))
self.dispose()
return None
def op_reject(self, params: Dict) -> Any:
error = (params.get("error") or {}).get("error") or {}
self._deliver(self.page, self.context_id, self.native, self.seq, False,
error.get("message") or error.get("name") or "binding failed")
self.dispose()
return None
class PageDispatcher(Dispatcher):
@@ -2718,8 +2810,6 @@ class PageDispatcher(Dispatcher):
"touchscreenTap": "op_touchscreen_tap",
"requests": "op_requests",
"__waitInfo__": "op_noop",
"reject": "op_binding_reply",
"resolve": "op_binding_reply",
"requestGC": "op_request_gc",
"addScriptTag": "op_add_script_tag",
"addStyleTag": "op_add_style_tag",
@@ -2923,6 +3013,14 @@ class PageDispatcher(Dispatcher):
#: to answer after a reader's pause, see `dialogs.plan_answer_ms`.
self._dialogs_open: Dict[str, Any] = {}
self._dialogs_seen = 0
#: `page.expose_binding` names -> the script that makes the function (see `_bindings`).
self._exposed: Dict[str, str] = {}
#: The calls of exposed functions, announced in the order they were made, by one worker (see `_on_binding_called`).
self._binding_jobs: "queue.Queue" = queue.Queue()
self._binding_running = False
self._binding_lock = threading.Lock()
#: (execution context, native name) -> objectId of the function that answers the calls made there (see `_bindings`).
self._binding_ends: Dict[tuple, str] = {}
self.main_frame_id = self._main_frame_unless_gone()
# ⛔ The Frame is created BEFORE the Page and adopted after: the Page
# initializer has to name a mainFrame the client can already resolve.
@@ -3179,6 +3277,7 @@ class PageDispatcher(Dispatcher):
frame.url, frame.name, frame.told_commit = url, name, commit
navigation = known._commits[-1][1] if known._commits else None
frame.emit("navigated", {"url": url, "name": name, "newDocument": self.navigation_document(navigation)})
frame.committed_url = url
for state in self.CANON_STATES:
if state in known.states and state not in frame.told_states:
frame.emit("loadstate", {"add": state})
@@ -3261,6 +3360,7 @@ class PageDispatcher(Dispatcher):
"newDocument": self.navigation_document(navigation),
})
child.emit("loadstate", {"add": "commit"})
child.committed_url = child.url
#: Events held while the page is being built. The birth of a page is a
#: burst of a few dozen; a page that never finishes building must not
@@ -3441,9 +3541,11 @@ class PageDispatcher(Dispatcher):
# Doing it here would block the reader waiting for a message the
# reader is the one who has to receive.
# ⛔ AND NOT STARTED HERE EITHER: `Thread.start` waits for the new thread to run, and this is the reader.
# The browser's thread starter does it (`_ThreadStarter`).
# The browser's thread starter does it (`ThreadStarter`).
self.context.browser.thread_starter.start(
target=self._announce_file_chooser, args=(params,))
elif method == "Page.bindingCalled":
self._on_binding_called(params)
elif method == "Page.crashed":
self.emit("crash")
# ⛔ `Page.frameAttached` / `Page.frameDetached` ARE NOT READ HERE: the
@@ -3472,6 +3574,15 @@ class PageDispatcher(Dispatcher):
# cannot disagree about a request, a redirect or a replay.
if method == "Network.requestWillBeSent" and params.get("isIntercepted"):
self._let_through(params.get("requestId"))
elif (method == "Network.requestWillBeSent" and params.get("method") == "OPTIONS"
and not params.get("isIntercepted")):
# ⛔ AS PLAYWRIGHT'S OWN SERVER (ffNetworkManager `_onRequestWillBeSent`: `if (event.method === "OPTIONS" &&
# !event.isIntercepted) return;`): an OPTIONS request that no route holds is a CORS preflight, which the browser
# makes for the page and the page cannot see; a client never hears of it. Reported here, a page with a
# preflighted fetch showed one request more than on stock Firefox (10 per page on cnbc.com, 18 on scmp.com),
# in `page.on("request")`, in `route`, in a request counter. Its response and its end find no request and are
# dropped with it.
pass
elif method == "Network.requestWillBeSent":
request = RequestDispatcher(self.server, self, params)
self._requests[params.get("requestId")] = request
@@ -4116,39 +4227,83 @@ class PageDispatcher(Dispatcher):
def op_requests(self, params: Dict) -> Any:
return {"requests": [r.channel for r in self._request_log]}
def op_binding_reply(self, params: Dict) -> Any:
"""⛔ `resolve` and `reject` are the REPLY half of `expose_binding`,
and they are unreachable while that is refused: they arrive on a
BindingCall object, and no BindingCall is ever created. This exists so
the refusal names the feature instead of answering "Page has no method
resolve", which would send the reader looking in the wrong place."""
raise ProtocolException(
"this is the reply path of expose_binding(), which is not "
"implemented: no binding is ever installed, so nothing can call "
"back into one")
# ── expose_binding / expose_function ────────────────────────────────────
def op_expose_binding(self, params: Dict) -> Any:
"""`expose_binding` / `expose_function`.
"""`page.expose_binding` / `page.expose_function`: the function `name` on this page, in the page's own world
(a site can see it, which is what the caller asked for, and nothing else: see `_bindings`). The engine installs it
in every document of the page, present and future, in every process the frames live in."""
name = params["name"]
native = self.context.binding_native(name)
self.context.require_binding_engine()
self._exposed[name] = native
self.send("Page.addBinding", {"name": native, "script": _bindings.install_script(native, name)})
⛔ THE PAGE-FACING HALF IS NOT THE HARD PART. Installing a function on
the page is one init script; what makes this a real feature is the
REPLY path - the page calls it, the server raises `bindingCalled`, the
client runs Python, and the answer has to travel back into the promise
the page is holding. That is what `reject` and `resolve` are for, and
they are only reachable through the BindingCall object this creates.
def undo() -> None:
self._exposed.pop(name, None)
self.send("Page.addBinding", {"name": native, "script": _bindings.remove_script(native, name)})
handle = DisposableDispatcher(self.server, self, undo)
return {"disposable": handle.channel}
⛔ AND THE FUNCTION MUST LIVE IN THE PAGE'S WORLD. Installed behind the
Xray it would be invisible to the site, which is the whole point of the
call. Juggler's `Page.addBinding` does that, so the world is not ours
to choose here - which is also why it cannot be hidden from the page:
a binding is a name the site can enumerate, and a caller asking for one
is asking for that trade.
"""
raise ProtocolException(
"expose_binding() is not implemented yet: the page-facing half is "
"one init script, but the reply path - bindingCalled, then resolve "
"or reject into the promise the page holds - is not wired, and a "
"binding that never answers hangs the page that called it")
def _on_binding_called(self, params: Dict) -> None:
"""The page called an exposed function. Announced to the client from a worker, in order, and not here.
OFF THE READER THREAD, because the announcement may need an answer from the engine (the address of the document
that called, see `_announce_binding`), which only the reader can deliver. In order, because two calls made one
after the other are announced one after the other: one worker per page, started by the first call and gone after
thirty idle seconds."""
payload = params.get("payload")
if isinstance(payload, dict) and payload.get("bindingEnd"):
# The page-side end of a binding, handed over by its script once, before any call: kept for the answers.
self._binding_ends[(params.get("executionContextId"), params.get("name"))] = payload["bindingEnd"]
return
call = _bindings.read_call(payload)
if call is None:
return
self._binding_jobs.put((params.get("executionContextId"), call))
with self._binding_lock:
if self._binding_running:
return
self._binding_running = True
# ⛔ NOT `Thread.start` HERE: this is the reader, and the browser's thread starter does it (`ThreadStarter`).
self.context.browser.thread_starter.start(target=self._binding_loop)
def _binding_loop(self) -> None:
while True:
try:
context_id, call = self._binding_jobs.get(timeout=30.0)
except queue.Empty:
with self._binding_lock:
if self._binding_jobs.empty():
self._binding_running = False
return
continue
try:
self._announce_binding(context_id, *call)
except Exception:
pass
def _announce_binding(self, context_id: str, name: str, seq: int, args: List[Any]) -> None:
"""A BindingCall to the client, or an error to the page when nobody exposed `name` here (left alone the
page's promise would wait for ever).
THE FRAME THE CLIENT IS TOLD OF HAS TO HAVE ITS ADDRESS. A script that calls the function in its first lines
runs before the lifecycle has told the client the document committed, and the call would name a frame whose
`url` is still the empty one. The address is asked of the document that called, and the call waits (a second
at most) until the client has been told that same address."""
injected = self.injected
native = self._exposed.get(name) or self.context._exposed.get(name)
if native is None:
return # nothing exposed under this name here: the page's promise cannot be answered, and was not offered
frame = self.frame_for(injected.frame_of_context(context_id) or self.frame.frame_id)
try:
href = injected.call_raw(context_id, "() => location.href", [], by_value=True, timeout=5.0).get("value")
except Exception:
href = None
end = time.monotonic() + 1.0
while href and frame.committed_url != href and time.monotonic() < end:
time.sleep(0.005)
binding = BindingCallDispatcher(self.server, self, frame, context_id, native, name, seq, args)
self.emit("bindingCall", {"binding": binding.channel})
def op_bring_to_front(self, params: Dict) -> Any:
self.send("Page.bringToFront", {})
@@ -4342,9 +4497,10 @@ class PageDispatcher(Dispatcher):
# too, because `_connection.py` only drops an object when it is told
# to. The driver disposes Page, BrowserContext, Browser, ElementHandle
# and APIRequestContext; the only one we were missing was Page, which
# is why `diff_protocol.py` grew a fifth dimension to see it: the other
# four compare `__create__`, initializers, events and parentage, and
# the event comparison skips every method starting with `__`.
# is why the protocol comparison that used to exist needed a fifth
# dimension to see it: the other four compared `__create__`, initializers,
# events and parentage, and the event comparison skips every method
# starting with `__`.
@@ -4488,6 +4644,7 @@ class BrowserContextDispatcher(Dispatcher):
"close": "op_close",
"updateSubscription": "op_noop",
"addInitScript": "op_context_init_script",
"exposeBinding": "op_expose_binding",
"addCookies": "op_add_cookies",
"cookies": "op_cookies",
"clearCookies": "op_clear_cookies",
@@ -4545,11 +4702,51 @@ class BrowserContextDispatcher(Dispatcher):
#: The caller's context-level init scripts, in order. The engine's
#: command replaces the list, so the accumulation lives here.
self._init_scripts: List[str] = []
#: `context.expose_binding` names -> the engine's native name for each (see `binding_native`).
self._exposed: Dict[str, str] = {}
self._native_names: Dict[str, str] = {}
self._transport_lock = threading.Lock()
@property
def conn(self) -> "juggler.Connection":
return self.browser.conn
def binding_native(self, name: str) -> str:
"""The name of the engine's native function for the exposed function `name`: unique to this context and this
session, chosen here (the page never sees it: its script takes it off the window before any script of the page)."""
with self._transport_lock:
native = self._native_names.get(name)
if native is None:
native = "__%s_%d" % (self.browser.binding_token, len(self._native_names))
self._native_names[name] = native
return native
def require_binding_engine(self) -> None:
"""Exposed functions need the engine that hands the page-side end of a binding over and has `Page.addBinding`.
With an engine that does not, they REFUSE: the way around it is a global on the window that a page can list,
and that is the tell this design exists to avoid."""
if not _bindings.engine_supports(self.browser.engine_dir):
raise ProtocolException(
"expose_function() and expose_binding() need a newer engine than this one (the one with "
"Page.addBinding and the binding that hands its end over): this engine would have to leave a "
"name on the page's window to answer the calls, and a page can list its globals")
def op_expose_binding(self, params: Dict) -> Any:
"""`context.expose_binding` / `context.expose_function`: the function `name` on every page of the context,
present and future. The engine installs it in every document of every page, in every process (see
`_bindings`); one registration, no init script, nothing run by this server in the documents."""
name = params["name"]
native = self.binding_native(name)
self.require_binding_engine()
self._exposed[name] = native
self._browser_send("Browser.addBinding", {"name": native, "script": _bindings.install_script(native, name)})
def undo() -> None:
self._exposed.pop(name, None)
self._browser_send("Browser.addBinding", {"name": native, "script": _bindings.remove_script(native, name)})
handle = DisposableDispatcher(self.server, self, undo)
return {"disposable": handle.channel}
def released(self) -> None:
"""⛔ THE BROWSER'S LIST LET GO TOO. Every way a context ends passes
here, and `browser.contexts` kept each one - with its options, its
@@ -4583,11 +4780,6 @@ class BrowserContextDispatcher(Dispatcher):
self._browser_send("Browser.setInitScripts",
{"scripts": [{"script": s}
for s in self._init_scripts]})
for page in list(self.pages):
try:
page.injected.add_init_script(source)
except Exception:
pass
handle = DisposableDispatcher(self.server, self,
lambda: self._remove_init_script(source))
return {"disposable": handle.channel}
@@ -4599,11 +4791,6 @@ class BrowserContextDispatcher(Dispatcher):
self._browser_send("Browser.setInitScripts",
{"scripts": [{"script": s}
for s in self._init_scripts]})
for page in list(self.pages):
try:
page.injected.remove_init_script(source)
except Exception:
pass
def op_set_storage_state(self, params: Dict) -> Any:
"""⛔ COOKIES ONLY, and it refuses the rest rather than dropping it.
@@ -4830,51 +5017,6 @@ NO_OVERRIDE = "no-override"
NO_OVERRIDE_OPTIONS = ("colorScheme", "reducedMotion", "forcedColors")
class _ThreadStarter:
"""The ONE long-lived thread that starts the other threads the engine's events ask for.
⛔ NO `Thread.start` ON THE CONNECTION'S READER THREAD. `Thread.start` does not return until the new thread is running
(`self._started.wait()`), and on Windows under load that wait is milliseconds long: it was the larger part of the reader's delay, and
every millisecond the reader is late is a millisecond a `networkidle` quiet is measured late (7 misses in 400 with four browsers at
once, none in 400 when the start did not wait). A listener that runs on the reader and needs work done elsewhere hands it to `start`
here: a `Thread` that is only BUILT on the reader (building waits for nothing) goes into a queue, and this thread starts it.
It starts threads and does not run the work itself, on purpose: an adoption waits for the engine as long as the engine takes (a popup
whose destination never answers is waited for without a limit), and a worker that ran it would hold every later adoption behind it,
`new_page()` included. Each piece of work keeps the thread of its own and the name it always had.
"""
def __init__(self, on_error: Callable[[str], None]) -> None:
self._queue: "queue.SimpleQueue" = queue.SimpleQueue()
self._on_error = on_error
self._stopped = False
self._thread = threading.Thread(target=self._run, daemon=True, name="invpw-thread-starter")
self._thread.start()
def start(self, **thread_arguments: Any) -> None:
"""Called from any thread, the reader's included: builds the thread and queues it. Never waits."""
if self._stopped:
return
self._queue.put(threading.Thread(daemon=True, **thread_arguments))
def stop(self) -> None:
self._stopped = True
self._queue.put(None)
def _run(self) -> None:
while True:
thread = self._queue.get()
if thread is None:
return
try:
thread.start()
except Exception as failure:
try:
self._on_error("%s could not be started: %s" % (thread.name, failure))
except Exception:
pass
class BrowserDispatcher(Dispatcher):
TYPE = "Browser"
METHODS = {"newContext": "op_new_context", "close": "op_close",
@@ -4947,6 +5089,10 @@ class BrowserDispatcher(Dispatcher):
#: Where this session measures a proxy's UDP exit from (the launch's `udp_stun_servers`, "ip:port"
#: strings; None = the two public defaults): the launch and every context proxy use the same list.
self.udp_stun_servers = udp_stun_servers
#: Chosen for this browser: the prefix of the native names of its exposed functions (see `_bindings`), and the
#: directory of its engine (set by `launch`), which says whether the engine has what they need.
self.binding_token = secrets.token_hex(6)
self.engine_dir = ""
#: Whether this browser's pages walk the pointer onto their targets
#: (`pointer.py`): the launcher chose the Python generator. Off for a
#: browser built without saying so, which acts as the caller wrote.
@@ -5063,8 +5209,9 @@ class BrowserDispatcher(Dispatcher):
# subscriber seeing an event before this one records the session, and
# recording earlier can only shorten the window in which `session_for`
# is waiting for something that has already arrived.
self._starter = _ThreadStarter(
lambda why: conn.handler_errors.append(why) if len(conn.handler_errors) < 32 else None)
# ⛔ NOT A STARTER OF ITS OWN: the connection's server owns the one (`Server.thread_starter`), and this is the browser's lease on
# it, ended by the browser's connection.
self._starter = ThreadStarterLease(lambda: server.thread_starter)
conn.add_close_listener(self._starter.stop)
conn.add_listener(self._route_browser_event)
# The last step of starting the browser, under what is left of the
@@ -5090,8 +5237,8 @@ class BrowserDispatcher(Dispatcher):
self._adopt_enabled = True
@property
def thread_starter(self) -> "_ThreadStarter":
"""The one thread that starts threads on behalf of the engine's reader (`_ThreadStarter`)."""
def thread_starter(self) -> "ThreadStarterLease":
"""What starts threads on behalf of the engine's reader: the connection's one starter (`Server.thread_starter`), while this browser lives."""
return self._starter
def require_interception(self, what: str) -> None:
@@ -6153,6 +6300,7 @@ class BrowserTypeDispatcher(Dispatcher):
except BaseException:
conn.close()
raise
browser.engine_dir = os.path.dirname(str(executable))
return {"browser": browser.channel}
+24 -8
View File
@@ -105,11 +105,25 @@ class InProcessTransport(Transport):
# ── the five methods the seam declares ──────────────────────────────────
async def connect(self) -> None:
for i in range(self.WORKERS):
t = threading.Thread(target=self._work, name="juggler-%d" % i,
daemon=True)
t.start()
self._threads.append(t)
"""⛔ NO `Thread.start` ON THE LOOP, NOT EVEN ONE. `connect` is a coroutine of the caller's event loop, and
`Thread.start` does not return until the new thread is running (`self._started.wait()`): measured with four
browsers in one process under CPU load on Windows, the four starts held the loop ~200 ms per launch (4.4% of the
main thread's wall time), the same wait the engine's reader is spared by the same starter.
The four `Thread` objects are only BUILT here (building waits for nothing), so `request_stop` still knows how many
sentinels the pool needs, and the server's one starter (`Server.thread_starter`, shared with every browser's reader) starts them. Messages sent before a worker runs wait in the queue and are
answered when it does, which is what `send` always relied on."""
self._threads = [
threading.Thread(target=self._work, name="juggler-%d" % i, daemon=True)
for i in range(self.WORKERS)]
server_starter = self._server.thread_starter
for t in self._threads:
server_starter.start_built(t, self._workers_could_not_start)
def _workers_could_not_start(self, why: str) -> None:
"""No worker may ever answer a queued message, so the session cannot go on: end it, the way a transport that lost
its other end ends, instead of leaving every call to wait for a reply that cannot come."""
self.request_stop()
async def run(self) -> None:
"""⛔ Must not return until the transport is stopped: `Connection.run`
@@ -138,7 +152,9 @@ class InProcessTransport(Transport):
async def wait_until_stopped(self) -> None:
await self._stopped_future
for t in self._threads:
t.join(timeout=5)
# A worker the starter never started (the transport stopped first) has nothing to join.
if t.is_alive():
t.join(timeout=5)
def send(self, message: Dict) -> None:
"""⛔ ENQUEUE ONLY. Running the operation here would run it on the
@@ -282,8 +298,8 @@ def make_transport(loop: asyncio.AbstractEventLoop) -> "InProcessTransport":
"only transport - unset %s and it runs. To get the old arm back "
"for a COMPARISON (the only thing it was still for): check out "
"the last commit that carried it into a git worktree and point "
"INVPW_DRIVER_TREE at it. Both `judge_both_transports.py` and "
"`diff_protocol.py` read that variable." % CHOICE_ENV)
"INVPW_DRIVER_TREE at it, which `scripts/capture_protocol.py` "
"reads." % CHOICE_ENV)
from .server import JugglerServer
if (os.environ.get(WIRE_ENV) or "").strip().lower() == "json":
return JsonWireTransport(loop, JugglerServer())
@@ -26,7 +26,7 @@ What each 1.62 addition becomes here:
target into view first, which is `auto`; `none` asks to act on the element
where it is, and honouring it needs an action path that does not scroll,
which does not exist. The action still happens, scrolled.
* `noGlobal` on exposeBinding: moot, `exposeBinding` is refused as a whole.
* `noGlobal` on exposeBinding: not read. The function is always defined on the page's `window`, as `expose_function` documents.
* `type` "webp" on screenshot: REFUSED. The engine captures PNG and JPEG, and
answering a webp request with PNG bytes would hand the caller a file that
is not the format it asked for.
@@ -102,5 +102,5 @@ class Transport(ABC):
#
# ⛔ To get the old arm back for a comparison - which is the only thing it
# was still for - check out the last commit that carried it into a git
# worktree and point `INVPW_DRIVER_TREE` at it. `judge_both_transports.py`
# and `diff_protocol.py` both read that variable.
# worktree and point `INVPW_DRIVER_TREE` at it. `scripts/capture_protocol.py`
# reads that variable.
+16 -7
View File
@@ -1,35 +1,44 @@
"""The check that no test module leaves a browser open.
A `BrowserDispatcher` starts one daemon thread, "invpw-thread-starter", and stops it only when the connection's close listeners fire. A
unit test that builds a dispatcher on a fake connection and never closes it leaves that thread alive, and the thread keeps the connection,
A connection's server owns ONE daemon thread, "invpw-thread-starter" (`Server.thread_starter`, made when the first thread is asked of it), and
stops it only on `shutdown`. A unit test that builds a dispatcher on a server and never shuts the server down leaves that thread alive, and the thread keeps the connection,
the browser and every context alive for the rest of the worker (a gc census of a closed context once found 7 of them, and one file alone
left 635). So the number of live starters, counted when the last test of a module has torn down, must be what it was before the module.
Module level and not per test: a module-scoped browser (the e2e ones) is legitimately open between its tests and closed at the end.
"""
import threading
import sys
import time
import pytest
STARTER_NAME = "invpw-thread-starter"
_THREADS_MODULE = "invisible_playwright._juggler._threads"
# `stop` is asynchronous: it queues a None and the thread leaves on its next turn. A moment, not a wait for a leak that will not leave.
_JOIN_SECONDS = 5.0
def starters_alive():
return [t for t in threading.enumerate() if t.name == STARTER_NAME and t.is_alive()]
"""The starters built and not ended, counted from their construction: `ThreadStarter` begins its thread without waiting for it, so
one that has not run yet is in no `threading.enumerate()` (a census of live threads missed 2 leaks on a Linux runner).
NO IMPORT HERE. A module that never loaded `_threads` cannot have built a starter, so the answer is empty without importing anything:
the census runs from conftest in every job, including ones that install pytest alone and have no `invisible_core` (the `version`
job failed on `invisible_playwright._pin` when this function imported the package)."""
threads = sys.modules.get(_THREADS_MODULE)
if threads is None:
return []
return threads.ThreadStarter.open_starters()
def wait_until_back_to(before, seconds=_JOIN_SECONDS):
"""The starters still alive after `seconds` beyond the `before` that were there already (0 when the module closed everything)."""
"""The starters still open after `seconds` beyond the `before` that were there already (0 when the module closed everything)."""
deadline = time.monotonic() + seconds
while True:
extra = len(starters_alive()) - before
if extra <= 0 or time.monotonic() >= deadline:
return max(extra, 0)
for t in starters_alive():
t.join(0.05)
time.sleep(0.05)
@pytest.fixture(scope="module", autouse=True)
+89
View File
@@ -0,0 +1,89 @@
"""The CPU the engine's processes use, by type of process, read from the processes of this test.
A Firefox browser is a tree: the parent, content processes (`tab`), and, where there are any, a GPU process (`gpu`), a socket process,
a media process (`rdd`) and utility processes. Every one but the parent is started with `-contentproc ... <type>` as the last argument
of its command line, so the type is read from there; no `-contentproc` is the parent.
`CpuSampler` reads the cumulative CPU time (user + kernel) of every engine process below the process that runs the test, every
`period` seconds, from a thread. A process that ends inside the window keeps the last value read before its end (at most one period of
its end is lost). The CPU of a type in a window is the sum, over its processes, of the last value minus the value at the start of the
window (zero for a process born after it).
The process of a test is the root: the browser a test starts is its descendant, and so is nothing else of the engine (an e2e run opens
several browsers at once, in several workers, each in its own process tree).
"""
from __future__ import annotations
import threading
import time
from typing import Dict, List, Tuple
TYPES = ("parent", "tab", "gpu", "socket", "rdd", "utility", "forkserver", "other")
def classify(cmdline: List[str]) -> str:
"""parent = no `-contentproc`; otherwise the last argument (tab, gpu, socket, rdd, utility, forkserver), `other` for any other."""
if "-contentproc" not in cmdline:
return "parent"
last = str(cmdline[-1]).strip('"').lower() if cmdline else "?"
return last if last in TYPES else "other"
def delta_by_type(start: Dict[int, Tuple[str, float]], last: Dict[int, Tuple[str, float]]) -> Dict[str, float]:
"""CPU seconds per type over a window: `start` and `last` map pid -> (type, cumulative CPU seconds)."""
out = {t: 0.0 for t in TYPES}
for pid, (kind, cpu) in last.items():
out[kind] = out.get(kind, 0.0) + max(0.0, cpu - start.get(pid, (kind, 0.0))[1])
return out
def engine_processes(root_pid: int) -> Dict[int, Tuple[str, float]]:
"""pid -> (type, cumulative CPU seconds) of every process named firefox below `root_pid`, now."""
import psutil
out: Dict[int, Tuple[str, float]] = {}
try:
below = psutil.Process(root_pid).children(recursive=True)
except psutil.Error:
return out
for proc in below:
try:
if not proc.name().lower().startswith("firefox"):
continue
times = proc.cpu_times()
out[proc.pid] = (classify(proc.cmdline()), times.user + times.system)
except psutil.Error:
continue
return out
class CpuSampler:
def __init__(self, root_pid: int, period: float = 0.25) -> None:
self.root_pid = root_pid
self.period = period
self.last: Dict[int, Tuple[str, float]] = {}
self.start: Dict[int, Tuple[str, float]] = {}
self._halt = threading.Event()
self._thread = threading.Thread(target=self._run, name="cpu-sampler", daemon=True)
def _take(self) -> None:
self.last.update(engine_processes(self.root_pid))
def _run(self) -> None:
while not self._halt.is_set():
self._take()
self._halt.wait(self.period)
def begin(self) -> None:
"""Mark the start of the window (what every process has used until now is not counted) and start sampling."""
self._take()
self.start = dict(self.last)
self._thread.start()
def end(self) -> Dict[str, float]:
"""Stop, take one more sample, and return the CPU seconds of the window by type."""
self._halt.set()
self._thread.join(timeout=10)
time.sleep(0.3)
self._take()
return delta_by_type(self.start, self.last)
+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))
+216
View File
@@ -0,0 +1,216 @@
"""What the page-bytes e2e needs, apart from the browser: the probe's values, the PNG comparison on decoded pixels, and the
comparison with a reference committed per operating system (tests/data/page_bytes_<os>.json).
The probe (tests/page_bytes_probe.js) resolves to a flat object {key: value} where a value is
{"s": "a short string"} a string of at most 3000 characters, or
{"h": ..., "n": ..., "s0": ...} a longer string: the hash of its bytes (cyrb53), its length, its first 200 characters, or
{"h": ..., "n": ..., "w": ..., "b64": ...} bytes: hash, length, pixels per row, the bytes themselves when at most 400 KiB.
A PNG that the page reads (toDataURL, toBlob, convertToBlob) also carries `b64`: the bytes of the file.
Two kinds of key in the reference:
"keys" stable values, equal in every launch: compared as they are (the string, or the hash and the length);
"pngs" the keys that are PNG files. A PNG the engine writes holds a 16-byte ancillary chunk, `deBG`, that differs in every
launch (measured on the Windows runner, run 43652292533: the same arm launched twice differs in that chunk and
nowhere else, the length is the same). So its bytes are not compared: its length, and the pixels it decodes to
(width, height, colour type, and the sha256 of the unfiltered scanlines).
No value here is made up: an entry the reference does not hold is a problem (the test is red), and the problem carries the
entry the run measured, in the form the reference file takes, so that a run on the engine of the day writes it down.
"""
from __future__ import annotations
import base64
import hashlib
import json
import struct
import zlib
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
DATA_PREFIX = "data:image/png;base64,"
#: the end of a key that is a PNG file (the jpeg and webp encodings are stable and are compared as they are)
PNG_KEY_ENDS = (".png", ".toBlob", ".convertToBlob", ".toDataURL")
DATA_DIR = Path(__file__).resolve().parent / "data"
# ------------------------------------------------------------------------------------------------------------------ PNG
class NotAPng(ValueError):
pass
def png_chunks(png: bytes) -> List[Tuple[bytes, bytes]]:
if not png.startswith(PNG_SIGNATURE):
raise NotAPng("no PNG signature")
out, i = [], len(PNG_SIGNATURE)
while i + 12 <= len(png):
size = struct.unpack(">I", png[i:i + 4])[0]
tag, data = png[i + 4:i + 8], png[i + 8:i + 8 + size]
if len(data) != size:
raise NotAPng("a chunk is cut")
out.append((tag, data))
i += 12 + size
return out
def _paeth(a: int, b: int, c: int) -> int:
p = a + b - c
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
return a if pa <= pb and pa <= pc else (b if pb <= pc else c)
def decode_png(png: bytes) -> Dict[str, Any]:
"""{w, h, ct, sha256} of a non-interlaced 8-bit PNG (grey, RGB, grey+alpha, RGBA): the sha256 is over the unfiltered
scanlines, so two files with the same pixels and different ancillary chunks or compression give the same answer."""
chunks = png_chunks(png)
head = [d for t, d in chunks if t == b"IHDR"]
if not head:
raise NotAPng("no IHDR")
w, h, depth, ct, _comp, _filt, interlace = struct.unpack(">IIBBBBB", head[0])
channels = {0: 1, 2: 3, 4: 2, 6: 4}.get(ct)
if depth != 8 or interlace != 0 or channels is None:
raise NotAPng("only 8-bit, non-interlaced, non-palette PNG is decoded here (bit depth %d, colour type %d, interlace %d)"
% (depth, ct, interlace))
raw = zlib.decompress(b"".join(d for t, d in chunks if t == b"IDAT"))
stride = w * channels
if len(raw) != h * (stride + 1):
raise NotAPng("the scanlines are %d bytes, %d expected" % (len(raw), h * (stride + 1)))
out = bytearray()
prev = bytearray(stride)
pos = 0
for _ in range(h):
ftype = raw[pos]
line = bytearray(raw[pos + 1:pos + 1 + stride])
pos += 1 + stride
if ftype == 1:
for i in range(channels, stride):
line[i] = (line[i] + line[i - channels]) & 255
elif ftype == 2:
for i in range(stride):
line[i] = (line[i] + prev[i]) & 255
elif ftype == 3:
for i in range(stride):
left = line[i - channels] if i >= channels else 0
line[i] = (line[i] + ((left + prev[i]) >> 1)) & 255
elif ftype == 4:
for i in range(stride):
left = line[i - channels] if i >= channels else 0
upleft = prev[i - channels] if i >= channels else 0
line[i] = (line[i] + _paeth(left, prev[i], upleft)) & 255
elif ftype != 0:
raise NotAPng("filter type %d" % ftype)
out += line
prev = line
return {"w": w, "h": h, "ct": ct, "sha256": hashlib.sha256(bytes(out)).hexdigest()}
def png_bytes_of(value: Dict[str, Any]) -> Optional[bytes]:
"""The PNG file a probe value holds, or None when the probe did not keep its bytes."""
if "b64" in value:
return base64.b64decode(value["b64"])
text = value.get("s")
if isinstance(text, str) and text.startswith(DATA_PREFIX):
return base64.b64decode(text[len(DATA_PREFIX):])
return None
def is_png_key(key: str) -> bool:
return key.endswith(PNG_KEY_ENDS)
# --------------------------------------------------------------------------------------------------------- the reference
def ident(value: Dict[str, Any]) -> Dict[str, Any]:
"""What identifies a stable value: its string, or the hash and the length of its bytes."""
if "s" in value:
return {"s": value["s"]}
return {"h": value.get("h"), "n": value.get("n")}
def png_entry(value: Dict[str, Any]) -> Dict[str, Any]:
"""The entry of a PNG key: its length and, when the bytes were kept, the pixels they decode to."""
# n: the length of the string for a data URL, of the file for bytes
entry: Dict[str, Any] = {"n": value["n"] if "n" in value else len(value.get("s", ""))}
data = png_bytes_of(value)
if data is None:
return entry
try:
entry.update(decode_png(data))
except (NotAPng, zlib.error) as exc:
entry["undecodable"] = str(exc)
return entry
def entry_of(key: str, value: Dict[str, Any]) -> Dict[str, Any]:
return png_entry(value) if is_png_key(key) else ident(value)
def reference_path(os_name: str) -> Path:
return DATA_DIR / ("page_bytes_%s.json" % os_name)
def load_reference(os_name: str) -> Dict[str, Any]:
"""The reference of an operating system; an empty one when the file does not exist yet (every key is then a problem
that carries its own entry, which is how the first reference is written)."""
path = reference_path(os_name)
if not path.is_file():
return {"keys": {}, "pngs": {}}
return json.loads(path.read_text(encoding="utf-8"))
def compare(reference: Dict[str, Any], measured: Dict[str, Dict[str, Any]]) -> Tuple[List[str], Dict[str, Dict[str, Any]]]:
"""(problems, record). `problems` is empty when every key the probe returned is in the reference with the same value
and the reference holds no key the probe did not return. `record` is the entry the run measured for every key that is
missing from the reference or incomplete in it (a PNG with no decoded pixels), in the form the reference file takes."""
problems: List[str] = []
record: Dict[str, Dict[str, Any]] = {}
stable, pngs = reference.get("keys", {}), reference.get("pngs", {})
for key in sorted(measured):
mine = entry_of(key, measured[key])
if is_png_key(key):
if "undecodable" in mine:
problems.append("%s: the PNG the page read does not decode (%s)" % (key, mine["undecodable"]))
continue
if "sha256" not in mine:
problems.append("%s: the probe did not keep the bytes of this PNG" % key)
continue
ref = pngs.get(key)
if ref is None:
problems.append("%s: not in the reference" % key)
record[key] = mine
elif ref.get("n") != mine.get("n"):
problems.append("%s: the PNG is %s bytes, the reference says %s" % (key, mine.get("n"), ref.get("n")))
elif "sha256" not in ref:
problems.append("%s: the reference has the length of this PNG and not yet its decoded pixels" % key)
record[key] = mine
elif (ref["w"], ref["h"], ref["ct"], ref["sha256"]) != (mine["w"], mine["h"], mine["ct"], mine["sha256"]):
problems.append("%s: the decoded pixels differ (%sx%s ct %s %s, the reference %sx%s ct %s %s)"
% (key, mine["w"], mine["h"], mine["ct"], mine["sha256"][:12],
ref["w"], ref["h"], ref["ct"], ref["sha256"][:12]))
else:
ref = stable.get(key)
if ref is None:
problems.append("%s: not in the reference" % key)
record[key] = mine
elif ref != mine:
problems.append("%s: %s, the reference %s" % (key, _short(mine), _short(ref)))
for key in sorted((set(stable) | set(pngs)) - set(measured)):
problems.append("%s: in the reference and not read by the probe" % key)
return problems, record
def _short(entry: Dict[str, Any], limit: int = 120) -> str:
return json.dumps(entry, sort_keys=True)[:limit]
def message(os_name: str, problems: List[str], record: Dict[str, Dict[str, Any]]) -> str:
"""The failure text: the problems, and the entries to add to tests/data/page_bytes_<os>.json."""
text = "%d problem(s) in the bytes a page reads on %s against %s:\n %s" % (
len(problems), os_name, reference_path(os_name).name, "\n ".join(problems[:60]))
if record:
keys = {k: v for k, v in record.items() if not is_png_key(k)}
pngs = {k: v for k, v in record.items() if is_png_key(k)}
text += ("\nTO RECORD (merge into tests/data/page_bytes_%s.json, from a run on the engine whose bytes are the reference):\n"
"RECORD-BEGIN %s\n%s\nRECORD-END" % (os_name, os_name, json.dumps({"keys": keys, "pngs": pngs}, sort_keys=True)))
return text
+328
View File
@@ -0,0 +1,328 @@
{
"os": "windows",
"source": "GitHub Actions run 43652292533 (workflow 'cpu render path hunt vm', job on windows-2022), arm `ours` = the published engine firefox-64_159.0_20261114003728 with the core the branch installed from the index (before the declaration of software compositing), seed 42, locale en-US, timezone Europe/Rome, headless=True; launched twice, and the arm `ours_vmretail` (the VM decisions of the new core) twice more: every key below is equal in the four launches. `pngs`: the PNG keys, whose bytes differ in a 16-byte chunk `deBG` in every launch; their length, and the pixels they decode to where the hunt kept the bytes (a data URL longer than 3000 characters was kept as hash and length only: those five entries have no `sha256` and are written by the first run of tests/test_the_bytes_a_page_reads_do_not_change_e2e.py on the engine of the reference). The keys of c2d.scale.*, c2d.gradtext.*, gpu.webgpu.features and gpu.webgpu.limits were added to the probe after that run (in it the WebGPU read threw `Xray wrapping of iterators not supported`, key gpu.webgpu.error, dropped here) and are in no reference yet.",
"keys": {
"c2d.composite.getImageData": {
"h": "df65ebe03bf31",
"n": 131072
},
"c2d.composite.jpeg": {
"h": "1c1b75006c5984",
"n": 11535
},
"c2d.composite.webp": {
"h": "182ab2238ae6c0",
"n": 5431
},
"c2d.image.getImageData": {
"h": "8218d41a1794c",
"n": 76800
},
"c2d.image.jpeg": {
"h": "125de65c968e30",
"n": 7315
},
"c2d.image.webp": {
"h": "26ea5dc80f98c",
"n": 5659
},
"c2d.measure": {
"h": "a731f7d3287e2",
"n": 9495
},
"c2d.offscreen.getImageData": {
"h": "1d9666b372acb1",
"n": 51200
},
"c2d.shapes.getImageData": {
"h": "18fe9a0f7336da",
"n": 163840
},
"c2d.shapes.jpeg": {
"h": "18d82802030ab3",
"n": 6975
},
"c2d.shapes.webp": {
"h": "1ec9fa4e39f8de",
"n": 3287
},
"c2d.text.getImageData": {
"h": "11041652732d2c",
"n": 856960
},
"c2d.text.jpeg": {
"h": "15a47ca2d73ab",
"n": 43163
},
"c2d.text.webp": {
"h": "59e03617b84b1",
"n": 26943
},
"dom.fonts_check": {
"s": "[[\"16px sans-serif\",true],[\"20px serif\",true],[\"18px monospace\",true],[\"bold 16px Arial\",true],[\"italic 15px 'Segoe UI'\",true],[\"16px 'Times New Roman'\",true],[\"16px Calibri\",true],[\"14px Consolas\",true],[\"16px Verdana\",true],[\"16px Tahoma\",true],[\"17px Georgia\",true],[\"16px 'Segoe UI Emoji'\",true],[\"16px 'Microsoft YaHei'\",true],[\"16px 'Yu Gothic'\",true]]"
},
"dom.paragraphs": {
"s": "[[\"16px sans-serif\",200,21],[\"15px 'Times New Roman'\",200,20],[\"14px Consolas\",200,19]]"
},
"dom.span_boxes": {
"h": "157207c863aeec",
"n": 5863
},
"dom.system_colors": {
"s": "[[\"Canvas\",\"rgb(255, 255, 255)\"],[\"CanvasText\",\"rgb(0, 0, 0)\"],[\"ButtonFace\",\"rgb(233, 233, 237)\"],[\"ButtonText\",\"rgb(0, 0, 0)\"],[\"ButtonBorder\",\"rgb(129, 127, 132)\"],[\"Field\",\"rgb(255, 255, 255)\"],[\"FieldText\",\"rgb(0, 0, 0)\"],[\"Highlight\",\"rgb(0, 120, 215)\"],[\"HighlightText\",\"rgb(255, 255, 255)\"],[\"GrayText\",\"rgb(109, 109, 109)\"],[\"LinkText\",\"rgb(0, 0, 238)\"],[\"VisitedText\",\"rgb(85, 26, 139)\"],[\"ActiveText\",\"rgb(238, 0, 0)\"],[\"Mark\",\"rgb(255, 255, 0)\"],[\"MarkText\",\"rgb(0, 0, 0)\"],[\"AccentColor\",\"rgb(0, 96, 223)\"],[\"AccentColorText\",\"rgb(255, 255, 255)\"],[\"SelectedItem\",\"rgb(0, 120, 215)\"],[\"SelectedItemText\",\"rgb(255, 255, 255)\"]]"
},
"env.dpr": {
"s": "1"
},
"env.hw": {
"s": "8"
},
"env.lang": {
"s": "[\"en-US\",\"en\"]"
},
"env.mq": {
"s": "[true,false,false,false,false,false,false]"
},
"env.oscpu": {
"s": "Windows NT 10.0; Win64; x64"
},
"env.platform": {
"s": "Win32"
},
"env.screen": {
"s": "[1920,1080,1920,1032,24,24]"
},
"env.ua": {
"s": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:159.0) Gecko/20100101 Firefox/159.0"
},
"gl1.anisotropy": {
"s": "16"
},
"gl1.antialias.false.readPixels": {
"h": "abed055e93fb8",
"n": 36864
},
"gl1.antialias.false.samples": {
"s": "0"
},
"gl1.antialias.true.readPixels": {
"h": "155744fc8af4b9",
"n": 36864
},
"gl1.antialias.true.samples": {
"s": "4"
},
"gl1.attributes": {
"s": "{\"alpha\":true,\"antialias\":true,\"depth\":true,\"failIfMajorPerformanceCaveat\":false,\"powerPreference\":\"default\",\"premultipliedAlpha\":true,\"preserveDrawingBuffer\":true,\"stencil\":false}"
},
"gl1.blend.readPixels": {
"h": "1e61b0c76b34d",
"n": 16384
},
"gl1.depth_stencil.readPixels": {
"h": "eaa3d5d41cfb",
"n": 16384
},
"gl1.extension_objects": {
"s": "[[\"ANGLE_instanced_arrays\",4],[\"EXT_blend_minmax\",2],[\"EXT_clip_control\",7],[\"EXT_color_buffer_half_float\",4],[\"EXT_depth_clamp\",1],[\"EXT_float_blend\",0],[\"EXT_frag_depth\",0],[\"EXT_polygon_offset_clamp\",2],[\"EXT_shader_texture_lod\",0],[\"EXT_sRGB\",4],[\"EXT_texture_compression_bptc\",4],[\"EXT_texture_compression_rgtc\",4],[\"EXT_texture_filter_anisotropic\",2],[\"EXT_texture_mirror_clamp_to_edge\",1],[\"OES_element_index_uint\",0],[\"OES_fbo_render_mipmap\",0],[\"OES_standard_derivatives\",1],[\"OES_texture_float\",0],[\"OES_texture_float_linear\",0],[\"OES_texture_half_float\",1],[\"OES_texture_half_float_linear\",0],[\"OES_vertex_array_object\",5],[\"WEBGL_color_buffer_float\",4],[\"WEBGL_compressed_texture_s3tc\",4],[\"WEBGL_compressed_texture_s3tc_srgb\",4],[\"WEBGL_debug_renderer_info\",2],[\"WEBGL_debug_shaders\",1],[\"WEBGL_depth_texture\",1],[\"WEBGL_draw_buffers\",35],[\"WEBGL_lose_context\",2],[\"WEBGL_provoking_vertex\",4]]"
},
"gl1.extensions": {
"s": "[\"ANGLE_instanced_arrays\",\"EXT_blend_minmax\",\"EXT_clip_control\",\"EXT_color_buffer_half_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_frag_depth\",\"EXT_polygon_offset_clamp\",\"EXT_shader_texture_lod\",\"EXT_sRGB\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"OES_element_index_uint\",\"OES_fbo_render_mipmap\",\"OES_standard_derivatives\",\"OES_texture_float\",\"OES_texture_float_linear\",\"OES_texture_half_float\",\"OES_texture_half_float_linear\",\"OES_vertex_array_object\",\"WEBGL_color_buffer_float\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_depth_texture\",\"WEBGL_draw_buffers\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"]"
},
"gl1.lines_points.readPixels": {
"h": "1841f80a258941",
"n": 16384
},
"gl1.math.highp.readPixels": {
"h": "85fe168c6de19",
"n": 16384
},
"gl1.math.mediump.readPixels": {
"h": "85fe168c6de19",
"n": 16384
},
"gl1.params": {
"s": "{\"VERSION\":\"WebGL 1.0\",\"SHADING_LANGUAGE_VERSION\":\"WebGL GLSL ES 1.0\",\"VENDOR\":\"Mozilla\",\"RENDERER\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"MAX_TEXTURE_SIZE\":16384,\"MAX_CUBE_MAP_TEXTURE_SIZE\":16384,\"MAX_RENDERBUFFER_SIZE\":16384,\"MAX_VIEWPORT_DIMS\":[32767,32767],\"ALIASED_LINE_WIDTH_RANGE\":[1,1],\"ALIASED_POINT_SIZE_RANGE\":[1,1024],\"MAX_VERTEX_ATTRIBS\":16,\"MAX_VARYING_VECTORS\":30,\"MAX_COMBINED_TEXTURE_IMAGE_UNITS\":32,\"MAX_VERTEX_TEXTURE_IMAGE_UNITS\":16,\"MAX_TEXTURE_IMAGE_UNITS\":16,\"MAX_VERTEX_UNIFORM_VECTORS\":4096,\"MAX_FRAGMENT_UNIFORM_VECTORS\":1024,\"RED_BITS\":8,\"GREEN_BITS\":8,\"BLUE_BITS\":8,\"ALPHA_BITS\":8,\"DEPTH_BITS\":24,\"STENCIL_BITS\":0,\"SAMPLES\":4,\"SAMPLE_BUFFERS\":1,\"SUBPIXEL_BITS\":4}"
},
"gl1.precision": {
"s": "[[\"VERTEX_SHADER\",\"LOW_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"LOW_INT\",31,30,0],[\"VERTEX_SHADER\",\"MEDIUM_INT\",31,30,0],[\"VERTEX_SHADER\",\"HIGH_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"LOW_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"LOW_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"MEDIUM_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"HIGH_INT\",31,30,0]]"
},
"gl1.texture.linear.readPixels": {
"h": "12a052fdb7d89f",
"n": 16384
},
"gl1.texture.mip.readPixels": {
"h": "12a052fdb7d89f",
"n": 16384
},
"gl1.texture.nearest.readPixels": {
"h": "160f810aa6835f",
"n": 16384
},
"gl1.triangle.drawImage": {
"h": "1f2476721e653d",
"n": 36864
},
"gl1.triangle.readPixels": {
"h": "e35b6ac5b7d59",
"n": 36864
},
"gl1.triangle.toDataURL_jpeg": {
"s": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCABgAGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxKiiivTPOCiiigAopDwOaro5MpfnB7e1enl+V1ceqjp/ZV/V9vnqJuyuWaKKK81pp2YwooopAFFFFABRRRQAUUUUAMlPy4HU0RR05U3NmrMUdfdZXbBYZR6vV/wBeR1VaHJTV9yMxHZkdqjrTijqre25hYMPuN+h9K8LOKMZT9vDrv/n/AJnl0qtpezl8itRRRXhHUFFFFABRRRQAUqjJxSVYt4+MnvW+GipVE3sjvy7CvE1kui1YsUdW4o6WKOrcUdevUx3mehjqe4kUdWTbrLEyOPlYYp8UdW4o64KuNvofG46DTujj7y3a1uGifnHIOOoqGu01LTRfW2wELIpyjEd/Q+1cYysjFXBVgcEEYINeepxk9DfB4pV42fxLf/MSiiimdgUUUUAOiQu4UfjWpFHjFQafD8pc9+BWnFHWM8Uqd0j7zJsv9hg1Vkvenr8un+fzEijq3FHSxR1bijriqY7zPPx1PcSKOrcUdLFHVuKOuCpjvM+Nx1PcSKOsHxdpDPF9ugUl0GJVUD7v978On0+ldTFHVuKOuVZk6U1JHys608LVVWHT8Txyit/xboR0m7WSBXNnL91jyEb+7n9Rn9cGsCvp6FeFeCqU3dM+qoV4YimqlN6MKdGhkdUXqTim1p6PAGLSnnHyipxNdYek6jPaybLpZljIYdbPf0W/9dy/DEFAAHAGBVuKOlijqYyQQsFmmjRsZwzAGvk54yU3Zas/VsfCFOOtkvuJIo6txR1SbUrCDbvuYzn+5838s0kniHT4du1pJc9didPzxWXLiqnwU2/kz4jH1qKuudfebMUdW4o65iTxbaogMFtM755DkKMfUZqGbxpNsAtrKNHzyZHLjH0GKn+zsfU2hb1a/wA7nyOLUZ/CzuIo6txR15rL4z1N4ika20THo6ISR+ZI/Sqc3ijWZomja+cKepRVQ/mACKa4fx1T4nFfN/oj53EZXUrbNI9XvtNh1KwltLkMYpRg7TgjnII+hArx3W9Mn0jUprS4VgVPyMRjeueGH1/+t2ok1fUpI2jk1C8eNgVZWnYgg9QRmqNe7lGWYjAOSnUTi+luve9/0Ncsy6rgpSvO8X0t17hUiTyooVJZFA7BiKjor25RUlaSue3TqzpO9OTT8tB0kjyHMjs5xjLHNNooppJKyJlJzfNJ3YUUUUCCiiigAooooAKKKKAP/9k="
},
"gl1.unmasked": {
"s": "[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"]"
},
"gl2.anisotropy": {
"s": "16"
},
"gl2.antialias.false.readPixels": {
"h": "abed055e93fb8",
"n": 36864
},
"gl2.antialias.false.samples": {
"s": "0"
},
"gl2.antialias.true.readPixels": {
"h": "155744fc8af4b9",
"n": 36864
},
"gl2.antialias.true.samples": {
"s": "4"
},
"gl2.attributes": {
"s": "{\"alpha\":true,\"antialias\":true,\"depth\":true,\"failIfMajorPerformanceCaveat\":false,\"powerPreference\":\"default\",\"premultipliedAlpha\":true,\"preserveDrawingBuffer\":true,\"stencil\":false}"
},
"gl2.blend.readPixels": {
"h": "1e61b0c76b34d",
"n": 16384
},
"gl2.depth_stencil.readPixels": {
"h": "eaa3d5d41cfb",
"n": 16384
},
"gl2.extension_objects": {
"s": "[[\"EXT_clip_control\",7],[\"EXT_color_buffer_float\",0],[\"EXT_depth_clamp\",1],[\"EXT_float_blend\",0],[\"EXT_polygon_offset_clamp\",2],[\"EXT_texture_compression_bptc\",4],[\"EXT_texture_compression_rgtc\",4],[\"EXT_texture_filter_anisotropic\",2],[\"EXT_texture_mirror_clamp_to_edge\",1],[\"EXT_texture_norm16\",8],[\"OES_draw_buffers_indexed\",7],[\"OES_texture_float_linear\",0],[\"OVR_multiview2\",5],[\"WEBGL_compressed_texture_s3tc\",4],[\"WEBGL_compressed_texture_s3tc_srgb\",4],[\"WEBGL_debug_renderer_info\",2],[\"WEBGL_debug_shaders\",1],[\"WEBGL_lose_context\",2],[\"WEBGL_provoking_vertex\",4]]"
},
"gl2.extensions": {
"s": "[\"EXT_clip_control\",\"EXT_color_buffer_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_polygon_offset_clamp\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"EXT_texture_norm16\",\"OES_draw_buffers_indexed\",\"OES_texture_float_linear\",\"OVR_multiview2\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"]"
},
"gl2.float_target.readPixels": {
"h": "4036e3357974d",
"n": 16384
},
"gl2.lines_points.readPixels": {
"h": "1841f80a258941",
"n": 16384
},
"gl2.math.highp.readPixels": {
"h": "85fe168c6de19",
"n": 16384
},
"gl2.math.mediump.readPixels": {
"h": "85fe168c6de19",
"n": 16384
},
"gl2.msaa_resolve.readPixels": {
"h": "1a2cbef856e591",
"n": 16384
},
"gl2.params": {
"s": "{\"VERSION\":\"WebGL 2.0\",\"SHADING_LANGUAGE_VERSION\":\"WebGL GLSL ES 3.00\",\"VENDOR\":\"Mozilla\",\"RENDERER\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"MAX_TEXTURE_SIZE\":16384,\"MAX_CUBE_MAP_TEXTURE_SIZE\":16384,\"MAX_RENDERBUFFER_SIZE\":16384,\"MAX_VIEWPORT_DIMS\":[32767,32767],\"ALIASED_LINE_WIDTH_RANGE\":[1,1],\"ALIASED_POINT_SIZE_RANGE\":[1,1024],\"MAX_VERTEX_ATTRIBS\":16,\"MAX_VARYING_VECTORS\":30,\"MAX_COMBINED_TEXTURE_IMAGE_UNITS\":32,\"MAX_VERTEX_TEXTURE_IMAGE_UNITS\":16,\"MAX_TEXTURE_IMAGE_UNITS\":16,\"MAX_VERTEX_UNIFORM_VECTORS\":4096,\"MAX_FRAGMENT_UNIFORM_VECTORS\":1024,\"RED_BITS\":8,\"GREEN_BITS\":8,\"BLUE_BITS\":8,\"ALPHA_BITS\":8,\"DEPTH_BITS\":24,\"STENCIL_BITS\":0,\"SAMPLES\":4,\"SAMPLE_BUFFERS\":1,\"SUBPIXEL_BITS\":4,\"MAX_3D_TEXTURE_SIZE\":2048,\"MAX_ARRAY_TEXTURE_LAYERS\":2048,\"MAX_COLOR_ATTACHMENTS\":8,\"MAX_DRAW_BUFFERS\":8,\"MAX_ELEMENTS_INDICES\":2147483647,\"MAX_ELEMENTS_VERTICES\":2147483647,\"MAX_FRAGMENT_INPUT_COMPONENTS\":120,\"MAX_FRAGMENT_UNIFORM_BLOCKS\":12,\"MAX_FRAGMENT_UNIFORM_COMPONENTS\":4096,\"MAX_PROGRAM_TEXEL_OFFSET\":7,\"MAX_SAMPLES\":8,\"MAX_SERVER_WAIT_TIMEOUT\":0,\"MAX_TEXTURE_LOD_BIAS\":2,\"MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS\":120,\"MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS\":4,\"MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS\":4,\"MAX_UNIFORM_BLOCK_SIZE\":65536,\"MAX_UNIFORM_BUFFER_BINDINGS\":24,\"MAX_VARYING_COMPONENTS\":120,\"MAX_VERTEX_OUTPUT_COMPONENTS\":120,\"MAX_VERTEX_UNIFORM_BLOCKS\":12,\"MAX_VERTEX_UNIFORM_COMPONENTS\":16384,\"MIN_PROGRAM_TEXEL_OFFSET\":-8,\"MAX_COMBINED_UNIFORM_BLOCKS\":24,\"MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS\":200704,\"MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS\":212992,\"UNIFORM_BUFFER_OFFSET_ALIGNMENT\":256}"
},
"gl2.precision": {
"s": "[[\"VERTEX_SHADER\",\"LOW_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"LOW_INT\",31,30,0],[\"VERTEX_SHADER\",\"MEDIUM_INT\",31,30,0],[\"VERTEX_SHADER\",\"HIGH_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"LOW_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"LOW_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"MEDIUM_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"HIGH_INT\",31,30,0]]"
},
"gl2.texture.linear.readPixels": {
"h": "12a052fdb7d89f",
"n": 16384
},
"gl2.texture.mip.readPixels": {
"h": "12a052fdb7d89f",
"n": 16384
},
"gl2.texture.nearest.readPixels": {
"h": "160f810aa6835f",
"n": 16384
},
"gl2.triangle.drawImage": {
"h": "1f2476721e653d",
"n": 36864
},
"gl2.triangle.readPixels": {
"h": "e35b6ac5b7d59",
"n": 36864
},
"gl2.triangle.toDataURL_jpeg": {
"s": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCABgAGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxKiiivTPOCiiigAopDwOaro5MpfnB7e1enl+V1ceqjp/ZV/V9vnqJuyuWaKKK81pp2YwooopAFFFFABRRRQAUUUUAMlPy4HU0RR05U3NmrMUdfdZXbBYZR6vV/wBeR1VaHJTV9yMxHZkdqjrTijqre25hYMPuN+h9K8LOKMZT9vDrv/n/AJnl0qtpezl8itRRRXhHUFFFFABRRRQAUqjJxSVYt4+MnvW+GipVE3sjvy7CvE1kui1YsUdW4o6WKOrcUdevUx3mehjqe4kUdWTbrLEyOPlYYp8UdW4o64KuNvofG46DTujj7y3a1uGifnHIOOoqGu01LTRfW2wELIpyjEd/Q+1cYysjFXBVgcEEYINeepxk9DfB4pV42fxLf/MSiiimdgUUUUAOiQu4UfjWpFHjFQafD8pc9+BWnFHWM8Uqd0j7zJsv9hg1Vkvenr8un+fzEijq3FHSxR1bijriqY7zPPx1PcSKOrcUdLFHVuKOuCpjvM+Nx1PcSKOsHxdpDPF9ugUl0GJVUD7v978On0+ldTFHVuKOuVZk6U1JHys608LVVWHT8Txyit/xboR0m7WSBXNnL91jyEb+7n9Rn9cGsCvp6FeFeCqU3dM+qoV4YimqlN6MKdGhkdUXqTim1p6PAGLSnnHyipxNdYek6jPaybLpZljIYdbPf0W/9dy/DEFAAHAGBVuKOlijqYyQQsFmmjRsZwzAGvk54yU3Zas/VsfCFOOtkvuJIo6txR1SbUrCDbvuYzn+5838s0kniHT4du1pJc9didPzxWXLiqnwU2/kz4jH1qKuudfebMUdW4o65iTxbaogMFtM755DkKMfUZqGbxpNsAtrKNHzyZHLjH0GKn+zsfU2hb1a/wA7nyOLUZ/CzuIo6txR15rL4z1N4ika20THo6ISR+ZI/Sqc3ijWZomja+cKepRVQ/mACKa4fx1T4nFfN/oj53EZXUrbNI9XvtNh1KwltLkMYpRg7TgjnII+hArx3W9Mn0jUprS4VgVPyMRjeueGH1/+t2ok1fUpI2jk1C8eNgVZWnYgg9QRmqNe7lGWYjAOSnUTi+luve9/0Ncsy6rgpSvO8X0t17hUiTyooVJZFA7BiKjor25RUlaSue3TqzpO9OTT8tB0kjyHMjs5xjLHNNooppJKyJlJzfNJ3YUUUUCCiiigAooooAKKKKAP/9k="
},
"gl2.unmasked": {
"s": "[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"]"
},
"gpu.webgpu.info": {
"s": "{\"vendor\":\"\",\"architecture\":\"\",\"device\":\"\",\"description\":\"\"}"
},
"worker.webgl": {
"s": "{\"vendor\":\"Mozilla\",\"renderer\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"unmasked\":[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"],\"exts\":[\"ANGLE_instanced_arrays\",\"EXT_blend_minmax\",\"EXT_clip_control\",\"EXT_color_buffer_half_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_frag_depth\",\"EXT_polygon_offset_clamp\",\"EXT_shader_texture_lod\",\"EXT_sRGB\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"OES_element_index_uint\",\"OES_fbo_render_mipmap\",\"OES_standard_derivatives\",\"OES_texture_float\",\"OES_texture_float_linear\",\"OES_texture_half_float\",\"OES_texture_half_float_linear\",\"OES_vertex_array_object\",\"WEBGL_color_buffer_float\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_depth_texture\",\"WEBGL_draw_buffers\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"],\"px\":[64,128,191,255,64,128,191,255,64,128,191,255,64,128,191,255]}"
}
},
"pngs": {
"c2d.composite.png": {
"n": 2414,
"w": 256,
"h": 128,
"ct": 6,
"sha256": "fb585f18240eb1a787a5b146d6332a0376dae76f8c8716e99f68fbbf9eff905e"
},
"c2d.composite.toBlob": {
"n": 1794,
"w": 256,
"h": 128,
"ct": 6,
"sha256": "fb585f18240eb1a787a5b146d6332a0376dae76f8c8716e99f68fbbf9eff905e"
},
"c2d.image.png": {
"n": 19502
},
"c2d.image.toBlob": {
"n": 14610,
"w": 160,
"h": 120,
"ct": 6,
"sha256": "51bc3789f2e238dfbf8899eb7a965a4f04d3e0e7f2246b1bd3cfdc9597bd2a77"
},
"c2d.offscreen.convertToBlob": {
"n": 2251,
"w": 160,
"h": 80,
"ct": 6,
"sha256": "55b4c78cd7b05627e9b2767477d61063b6849a7636c5be2ce0a62c6a2c6c9cc4"
},
"c2d.shapes.png": {
"n": 19226
},
"c2d.shapes.toBlob": {
"n": 14402,
"w": 256,
"h": 160,
"ct": 6,
"sha256": "89ee57c100f4682099bd3a5f2de56c5b31091dae253bd7e3db4f254fb8b9e6a3"
},
"c2d.text.png": {
"n": 42670
},
"c2d.text.toBlob": {
"n": 31986,
"w": 520,
"h": 412,
"ct": 6,
"sha256": "93d6fc37d2263e52e7b1b46f77c65d9e607faf577eb7c255dc38cbce8b7d7602"
},
"gl1.triangle.toDataURL": {
"n": 7474
},
"gl2.triangle.toDataURL": {
"n": 7474
}
}
}
-21
View File
@@ -1,21 +0,0 @@
{
"_why": "The four rules the Node driver's user.js writer follows, FROZEN. Until 2026-08-28 prefs_byte_parity.py read them out of src/invisible_playwright/_driver/package/lib/coreBundle.js on every run, deliberately, so that an upstream change moved the gate with it instead of leaving it comparing against a stale transcription. The bundle is being deleted with the Node driver, so the derived fact becomes a recorded one - and this file exists to make that visible rather than silent.",
"_how_to_verify": "While a bundle is still reachable, prefs_byte_parity.py re-extracts and compares against these values, and FAILS on a mismatch. To reach one after the deletion: git worktree add <dir> <the last commit that carried _driver/>, then point the gate at it with INVPW_DRIVER_BUNDLE=<dir>/src/invisible_playwright/_driver/package/lib/coreBundle.js.",
"_what_a_stale_copy_would_cost": "The gate would compare our writer against our own idea of the driver, which always agrees. That is the failure mode the run-time read existed to prevent, and it is why the provenance below is recorded to the byte instead of just being dated.",
"rules": {
"sorts": false,
"header": false,
"separator": true,
"integer_bare": true
},
"provenance": {
"frozen_on": "2026-08-28",
"file": "src/invisible_playwright/_driver/package/lib/coreBundle.js",
"bundle_bytes": 2780363,
"bundle_sha256_16": "97d55ec7f856966d",
"marker": "__ipwLit",
"marker_offset": 1775227,
"window_bytes": 1200,
"window_sha256_16": "4891de086d6625f6"
}
}
-243
View File
@@ -1,243 +0,0 @@
"""The two writers must produce the SAME `user.js`, byte for byte.
⛔ THIS IS THE CRITERION ITEM 1 WAS WRITTEN WITH, and it is stricter than
"both work" on purpose. Two prefs files can each be valid, each configure the
browser, and differ - a header comment, a different order, an integer written
as a string. Every one of those differences is invisible in a running browser
and every one of them means the Python path is configuring a browser the Node
path never configured. The whole point of keeping the driver as a judge is that
this comparison is possible; a looser check throws that away.
⛔ AND IT NEEDS NO BROWSER. Both writers are pure functions of the prefs dict:
the driver's is a JavaScript literal builder inside `coreBundle.js`, ours is
`invisible_core.launch.write_user_js`, the one writer since 0.30.0. The driver's rules are re-implemented here FROM ITS SOURCE,
read at run time rather than copied - so if upstream's writer changes, this gate
changes with it instead of silently comparing against a stale transcription.
python tests/gates/prefs_byte_parity.py
python tests/gates/prefs_byte_parity.py --selftest # 6 mutations, 3 that must not fire
"""
from __future__ import annotations
import argparse
import json
import os
import pathlib
import re
import sys
import tempfile
ROOT = pathlib.Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(ROOT / "src"))
BUNDLE = ROOT / "src/invisible_playwright/_driver/package/lib/coreBundle.js"
#: A prefs dict shaped like a real one: the four value kinds that matter, a
#: name with a character JSON has to escape, and a deliberately unsorted order.
#: ⛔ THE ORDER IS PART OF THE FIXTURE. The driver uses `Object.keys()`, so a
#: writer that sorts produces a file that is equally correct and not identical,
#: and that is precisely the class of difference this gate exists to catch.
SAMPLE = {
"zoom.stealth.screen.width": 1920,
"app.update.auto": False,
"layout.css.devPixelsPerPx": "1.25",
"ui.textScaleFactor": 1.0,
"general.useragent.override": 'Mozilla/5.0 "quoted" \\ backslash',
"browser.startup.homepage": "about:blank",
}
class DriverRulesMissing(RuntimeError):
pass
#: The frozen copy, with its provenance. See the file itself for why.
FROZEN = pathlib.Path(__file__).resolve().parent / "driver_prefs_rules.json"
#: Where to find a bundle after the deletion: a git worktree at the last commit
#: that carried `_driver/`. Named here so the gate can say it out loud instead
#: of leaving the reader to work it out.
BUNDLE_ENV = "INVPW_DRIVER_BUNDLE"
def _bundle():
"""A reachable bundle, or None. Never raises: absence is a state."""
named = os.environ.get(BUNDLE_ENV)
if named:
candidate = pathlib.Path(named)
return candidate if candidate.exists() else None
return BUNDLE if BUNDLE.exists() else None
def driver_rules() -> dict:
"""The driver's literal rules: frozen, and re-checked whenever possible.
⛔ IT USED TO READ THE BUNDLE ON EVERY RUN, deliberately, so an upstream
change moved this gate with it instead of leaving it comparing against a
stale transcription. The bundle goes with the Node driver, so the rules are
now RECORDED - in `driver_prefs_rules.json`, with the sha of the bundle and
of the exact 1200-byte window they came from.
⛔ AND THE RE-CHECK IS THE WHOLE POINT OF FREEZING THEM THIS WAY. Whenever a
bundle IS reachable - still in the tree, or named by `INVPW_DRIVER_BUNDLE`
from a git worktree - the rules are extracted again and compared against the
frozen copy, and a mismatch FAILS. A recorded fact nobody can re-derive is a
transcription, and a transcription this gate cannot check is exactly what
the original design refused to have.
"""
frozen = json.loads(FROZEN.read_text(encoding="utf-8"))["rules"]
bundle = _bundle()
if bundle is None:
return frozen
live = _extract(bundle.read_text(encoding="utf-8", errors="replace"))
if live != frozen:
raise DriverRulesMissing(
"the frozen driver rules disagree with the bundle at %s.\n"
" frozen: %s\n bundle: %s\n"
"The frozen copy is stale: re-freeze it with the new provenance, "
"rather than loosening this comparison." % (bundle, frozen, live))
return frozen
def _extract(text: str) -> dict:
start = text.find("__ipwLit")
if start < 0:
raise DriverRulesMissing(
"the driver's pref writer is not in the bundle: it was renamed or "
"removed, and this gate cannot compare against something it "
"cannot read")
window = text[start:start + 1200]
return {
"sorts": "sort()" in window,
"header": bool(re.search(r'"//[^"]*"\s*\+', window)),
"separator": "String.fromCharCode(10)" in window or "\\n" in window,
"integer_bare": "Number.isInteger" in window,
}
def driver_user_js(prefs: dict) -> str:
"""What the driver writes, in Python, following the rules read above."""
rules = driver_rules()
names = sorted(prefs) if rules["sorts"] else list(prefs)
lines = []
for name in names:
value = prefs[name]
if isinstance(value, bool):
literal = "true" if value else "false"
elif isinstance(value, int):
literal = str(value)
elif isinstance(value, float):
# ⛔ Not an integer, so the driver quotes it: Gecko has no float
# pref type, and a bare fraction makes the parser fail and IGNORE
# EVERY LINE AFTER IT.
literal = json.dumps(str(value))
else:
literal = json.dumps(str(value))
lines.append("user_pref(%s, %s);" % (json.dumps(name), literal))
head = "// header\n" if rules["header"] else ""
return head + "\n".join(lines) + "\n"
def ours(prefs: dict) -> str:
from invisible_core.launch import write_user_js
directory = tempfile.mkdtemp(prefix="prefs_parity_")
write_user_js(directory, prefs)
return (pathlib.Path(directory) / "user.js").read_bytes().decode("utf-8")
def compare(prefs: dict) -> list:
theirs = driver_user_js(prefs)
mine = ours(prefs)
if theirs == mine:
return []
faults = []
a, b = theirs.splitlines(), mine.splitlines()
if len(a) != len(b):
faults.append("line count: driver %d, ours %d" % (len(a), len(b)))
for i, (x, y) in enumerate(zip(a, b)):
if x != y:
faults.append("line %d:\n driver: %s\n ours : %s"
% (i + 1, x, y))
if not faults:
faults.append("same lines, different bytes: trailing newline or "
"encoding")
return faults
# ── the selftest ────────────────────────────────────────────────────────────
def selftest() -> int:
bad = 0
def expect(name, produce, should_fire):
nonlocal bad
theirs = driver_user_js(SAMPLE)
mine = produce(theirs)
differs = theirs != mine
if differs != should_fire:
print(" %s: %s" % ("SURVIVED" if should_fire else "FALSE POSITIVE",
name))
bad += 1
else:
print(" %s: %s" % ("killed" if should_fire else "silent", name))
print("--- mutations that MUST fire ---")
expect("a header comment is added",
lambda t: "// written by us\n" + t, True)
expect("the lines are sorted",
lambda t: "\n".join(sorted(t.splitlines())) + "\n", True)
expect("an integer is quoted",
lambda t: t.replace("user_pref(\"zoom.stealth.screen.width\", 1920)",
"user_pref(\"zoom.stealth.screen.width\", \"1920\")"),
True)
expect("a boolean becomes a string",
lambda t: t.replace(", false)", ", \"false\")"), True)
expect("the trailing newline is dropped",
lambda t: t.rstrip("\n"), True)
expect("one pref goes missing",
lambda t: "\n".join(t.splitlines()[1:]) + "\n", True)
print("--- cases that must NOT fire ---")
expect("the same text", lambda t: t, False)
expect("the same text built twice", lambda t: driver_user_js(SAMPLE), False)
expect("a float stays quoted",
lambda t: t.replace('"1.0"', '"1.0"'), False)
print()
print("selftest: %s" % ("ALL GOOD" if not bad else "%d PROBLEMS" % bad))
return 1 if bad else 0
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--selftest", action="store_true")
a = p.parse_args()
if a.selftest:
return selftest()
try:
rules = driver_rules()
except DriverRulesMissing as failure:
print("NOT COMPARABLE: %s" % failure)
return 2
# ⛔ IT SAYS WHICH SOURCE IT USED. The line used to read "driver rules read
# from the bundle" unconditionally, and after the freeze that sentence was
# simply false half the time - a gate that misreports where its own
# reference came from is worse than one with no message, because the reader
# stops looking.
bundle = _bundle()
print("driver rules %s: %s"
% ("re-checked against %s" % bundle if bundle
else "from the FROZEN copy (%s) - no bundle reachable, so nothing "
"re-derived them this run" % FROZEN.name,
", ".join("%s=%s" % kv for kv in sorted(rules.items()))))
faults = compare(SAMPLE)
if not faults:
print("PREFS BYTE PARITY: identical (%d prefs)" % len(SAMPLE))
return 0
print("the two writers DISAGREE:")
for f in faults:
print(" " + f)
return 1
if __name__ == "__main__":
sys.exit(main())
+475
View File
@@ -0,0 +1,475 @@
// The probe of tests/test_the_bytes_a_page_reads_do_not_change_e2e.py: one expression that resolves to a flat object
// {key: {s: "a short string"} | {h, n, s0} | {h, n, w, b64}} of everything a page can read about drawing and text:
// c2d.* canvas 2D: getImageData bytes, toDataURL (png, jpeg, webp), toBlob, OffscreenCanvas.convertToBlob, measureText; drawImage scaled up
// and down with imageSmoothing off and on at every imageSmoothingQuality (c2d.scale.*); gradients (linear, radial, conic) filling and
// stroking text (c2d.gradtext)
// gl1.* WebGL 1 and gl2.* WebGL 2: strings, extensions, limits, precision formats, readPixels bytes of several scenes, toDataURL, drawImage of the canvas
// worker.* an OffscreenCanvas WebGL context in a worker
// gpu.* the WebGPU adapter
// dom.* text layout: the boxes of spans in many fonts, wrapped paragraphs, system colours
// env.* the values the persona declares around it
// A PNG the page reads (toDataURL, toBlob, convertToBlob) keeps its bytes in `b64`: the test compares the pixels it decodes to, because the engine
// writes a per-launch ancillary chunk into every PNG (tests/_page_bytes.py). Every scene is wrapped: an exception becomes `<scene>.error` and is
// compared like any other value, so every launch gives the same keys.
// Taken from the hunt that measured the Windows reference (scripts/hunt_page_bytes_probe.js of run 43652292533), with its encoding mode removed.
(async () => {
const out = {};
const enc = new TextEncoder();
function hashBytes(u8) { // cyrb53 over bytes: no crypto.subtle (it needs a secure context)
let h1 = 0xdeadbeef ^ u8.length, h2 = 0x41c6ce57 ^ u8.length;
for (let i = 0; i < u8.length; i++) { const ch = u8[i]; h1 = Math.imul(h1 ^ ch, 2654435761); h2 = Math.imul(h2 ^ ch, 1597334677); }
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16);
}
function b64(u8) {
let s = "";
for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000));
return btoa(s);
}
function put(k, v, w) {
if (ArrayBuffer.isView(v) || v instanceof ArrayBuffer) {
const u8 = v instanceof ArrayBuffer ? new Uint8Array(v) : new Uint8Array(v.buffer, v.byteOffset, v.byteLength);
out[k] = { h: hashBytes(u8), n: u8.length };
if (w) { out[k].w = w; out[k].bpp = 4 * (v.BYTES_PER_ELEMENT || 1); } // pixels per row, bytes per pixel (RGBA)
if (u8.length <= 400 * 1024) out[k].b64 = b64(u8);
} else {
const s = typeof v === "string" ? v : JSON.stringify(v);
out[k] = s.length <= 3000 ? { s } : { h: hashBytes(enc.encode(s)), n: s.length, s0: s.slice(0, 200) };
if (s.length > 3000 && s.startsWith("data:image/png;base64,") && s.length <= 600 * 1024) out[k].b64 = s.slice(22);
}
}
async function scene(k, fn) {
try { await fn(); } catch (e) { put(k + ".error", String((e && e.message) || e)); }
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// ------------------------------------------------------------------------------------------------------------ env
await scene("env", async () => {
put("env.ua", navigator.userAgent);
put("env.platform", navigator.platform);
put("env.oscpu", navigator.oscpu || "");
put("env.hw", navigator.hardwareConcurrency);
put("env.lang", navigator.languages);
put("env.dpr", window.devicePixelRatio);
put("env.screen", [screen.width, screen.height, screen.availWidth, screen.availHeight, screen.colorDepth, screen.pixelDepth]);
put("env.mq", ["(color-gamut: srgb)", "(color-gamut: p3)", "(dynamic-range: high)", "(prefers-color-scheme: dark)", "(prefers-reduced-motion: reduce)",
"(forced-colors: active)", "(inverted-colors: inverted)"].map((q) => matchMedia(q).matches));
});
// ---------------------------------------------------------------------------------------------------- canvas 2D
function c2d(w, h) { const c = document.createElement("canvas"); c.width = w; c.height = h; return [c, c.getContext("2d")]; }
function dataUrlBytes(url) {
const bin = atob(url.split(",")[1]);
const u = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i);
return u;
}
async function read2d(k, c, g) {
put(k + ".getImageData", g.getImageData(0, 0, c.width, c.height).data, c.width);
put(k + ".png", c.toDataURL());
put(k + ".jpeg", c.toDataURL("image/jpeg", 0.8));
put(k + ".webp", c.toDataURL("image/webp", 0.8));
const blob = await new Promise((r) => c.toBlob(r));
put(k + ".toBlob", blob ? new Uint8Array(await blob.arrayBuffer()) : "null");
}
await scene("c2d.shapes", async () => {
const [c, g] = c2d(256, 160);
g.fillStyle = "#fff"; g.fillRect(0, 0, 256, 160);
const lg = g.createLinearGradient(0, 0, 256, 0);
lg.addColorStop(0, "#f00"); lg.addColorStop(0.5, "rgba(0,200,0,.5)"); lg.addColorStop(1, "#00f");
g.fillStyle = lg; g.fillRect(8, 8, 240, 40);
const rg = g.createRadialGradient(60, 100, 4, 60, 100, 50);
rg.addColorStop(0, "#ff0"); rg.addColorStop(1, "rgba(255,0,255,.2)");
g.fillStyle = rg; g.beginPath(); g.arc(60, 100, 50, 0, Math.PI * 2); g.fill();
g.strokeStyle = "#123"; g.lineWidth = 1.5; g.beginPath(); g.moveTo(130, 60); g.bezierCurveTo(160, 20, 200, 140, 240, 70); g.stroke();
g.lineWidth = 0.7; g.beginPath(); g.ellipse(190, 110, 40, 20, 0.5, 0, Math.PI * 2); g.stroke();
g.save(); g.shadowColor = "rgba(0,0,0,.6)"; g.shadowBlur = 6; g.shadowOffsetX = 3; g.shadowOffsetY = 3; g.fillStyle = "#38c"; g.fillRect(120, 100, 50, 30); g.restore();
g.save(); g.translate(30, 140); g.rotate(0.3); g.scale(1.3, 0.8); g.fillStyle = "#a40"; g.fillRect(0, 0, 40, 20); g.restore();
if (g.createConicGradient) {
const cg = g.createConicGradient(0.5, 215, 140);
cg.addColorStop(0, "#f80"); cg.addColorStop(0.5, "#08f"); cg.addColorStop(1, "#f80");
g.fillStyle = cg; g.fillRect(190, 120, 60, 36);
}
await read2d("c2d.shapes", c, g);
});
await scene("c2d.composite", async () => {
const ops = ["source-over", "source-in", "source-out", "source-atop", "destination-over", "destination-in", "destination-out", "destination-atop",
"lighter", "copy", "xor", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light",
"difference", "exclusion", "hue", "saturation", "color", "luminosity"];
const [c, g] = c2d(8 * 32, 4 * 32);
ops.forEach((op, i) => {
const x = (i % 8) * 32, y = Math.floor(i / 8) * 32;
g.save(); g.beginPath(); g.rect(x, y, 32, 32); g.clip();
g.globalCompositeOperation = "source-over";
g.fillStyle = "rgba(200,60,40,.8)"; g.fillRect(x + 2, y + 2, 20, 20);
g.globalCompositeOperation = op;
g.fillStyle = "rgba(30,90,220,.6)"; g.fillRect(x + 10, y + 10, 20, 20);
g.restore();
});
await read2d("c2d.composite", c, g);
});
await scene("c2d.filter_draw_image", async () => {
const [c, g] = c2d(160, 120);
const [s, sg] = c2d(10, 10);
for (let i = 0; i < 100; i++) { sg.fillStyle = "hsl(" + ((i * 37) % 360) + ",70%,50%)"; sg.fillRect(i % 10, Math.floor(i / 10), 1, 1); }
g.imageSmoothingEnabled = true; g.imageSmoothingQuality = "high";
g.drawImage(s, 0, 0, 10, 10, 5.5, 5.5, 70.3, 70.3);
g.imageSmoothingEnabled = false; g.drawImage(s, 80, 5, 60, 60);
if ("filter" in g) { g.filter = "blur(2px) saturate(1.4)"; g.drawImage(s, 5, 70, 40, 40); g.filter = "none"; }
const p = g.createPattern(s, "repeat"); g.fillStyle = p; g.fillRect(60, 70, 90, 40);
const d = g.getImageData(0, 0, 40, 40); g.putImageData(d, 100, 80);
await read2d("c2d.image", c, g);
});
const FONTS = ["16px sans-serif", "20px serif", "18px monospace", "bold 16px Arial", "italic 15px 'Segoe UI'", "16px 'Times New Roman'", "16px Calibri",
"14px Consolas", "16px Verdana", "16px Tahoma", "17px Georgia", "16px 'Segoe UI Emoji'", "16px 'Microsoft YaHei'", "16px 'Yu Gothic'"];
const TEXTS = ["Hamburgefonstiv 0123456789", "The quick brown fox jumps over the lazy dog", "ÀÉÎÕÜ ß fi fl ffl", "日本語のテキスト 漢字", "😀🚀👍🏽", "مرحبا بالعالم"];
await scene("c2d.text", async () => {
const [c, g] = c2d(520, FONTS.length * 28 + 20);
g.fillStyle = "#fff"; g.fillRect(0, 0, c.width, c.height);
FONTS.forEach((f, i) => {
g.font = f; g.fillStyle = "#101820"; g.textBaseline = "alphabetic";
g.fillText(TEXTS[i % TEXTS.length], 6, 22 + i * 28);
g.strokeStyle = "rgba(200,0,0,.8)"; g.lineWidth = 0.6; g.strokeText("Ag", 470, 22 + i * 28);
});
await read2d("c2d.text", c, g);
const m = [];
for (const f of FONTS) {
g.font = f;
for (const t of TEXTS) {
const r = g.measureText(t);
m.push([f, t, r.width, r.actualBoundingBoxLeft, r.actualBoundingBoxRight, r.actualBoundingBoxAscent, r.actualBoundingBoxDescent,
r.fontBoundingBoxAscent, r.fontBoundingBoxDescent]);
}
}
put("c2d.measure", m);
});
await scene("c2d.offscreen", async () => {
if (typeof OffscreenCanvas === "undefined") { put("c2d.offscreen", "no OffscreenCanvas"); return; }
const oc = new OffscreenCanvas(160, 80), g = oc.getContext("2d");
g.fillStyle = "#fed"; g.fillRect(0, 0, 160, 80); g.fillStyle = "rgba(10,120,200,.7)"; g.beginPath(); g.arc(50, 40, 30, 0, 6.2); g.fill();
g.font = "bold 18px sans-serif"; g.fillStyle = "#222"; g.fillText("offscreen 2d", 70, 45);
put("c2d.offscreen.getImageData", g.getImageData(0, 0, 160, 80).data, 160);
const blob = await oc.convertToBlob();
put("c2d.offscreen.convertToBlob", new Uint8Array(await blob.arrayBuffer()));
});
// ----------------------------------------------------------------------------------------- drawImage scaled, smoothing and quality
// A 24x24 source with hard edges and a ramp, a 200x200 one (to scale down), each drawn up and down, rotated and not, with imageSmoothing off and
// on at low, medium and high. The pixels (getImageData) and the PNG of the same canvas, which the test compares decoded.
await scene("c2d.scale", async () => {
const [s1, sg1] = c2d(24, 24);
for (let y = 0; y < 24; y++) for (let x = 0; x < 24; x++) {
sg1.fillStyle = (x + y) % 5 === 0 ? "#000" : "hsl(" + ((x * 13 + y * 7) % 360) + "," + (40 + (y * 2)) + "%," + (30 + x) + "%)";
sg1.fillRect(x, y, 1, 1);
}
const [s2, sg2] = c2d(200, 200);
for (let i = 0; i < 40; i++) {
sg2.fillStyle = "hsl(" + (i * 9) + ",70%,50%)"; sg2.fillRect((i * 17) % 190, (i * 29) % 190, 23 + (i % 7), 11 + (i % 5));
sg2.strokeStyle = i % 2 ? "#fff" : "#111"; sg2.lineWidth = 1; sg2.beginPath(); sg2.moveTo(i * 5, 0); sg2.lineTo(200 - i * 4, 200); sg2.stroke();
}
const configs = [["off", false, "low"], ["low", true, "low"], ["medium", true, "medium"], ["high", true, "high"]];
for (const [name, on, quality] of configs) {
const [c, g] = c2d(220, 130);
g.fillStyle = "#fff"; g.fillRect(0, 0, 220, 130);
g.imageSmoothingEnabled = on; g.imageSmoothingQuality = quality;
g.drawImage(s1, 0, 0, 24, 24, 3.25, 3.25, 97.3, 97.3); // up, not an integer factor
g.drawImage(s2, 0, 0, 200, 200, 110.5, 4.5, 37, 37); // down, far
g.drawImage(s2, 20, 20, 120, 120, 150, 4, 61, 61); // down, near, a part of the source
g.drawImage(s1, 0, 0, 24, 24, 110, 50, 24, 24); // 1:1 at a whole pixel
g.save(); g.translate(180, 95); g.rotate(0.35); g.drawImage(s1, 0, 0, 24, 24, -20, -20, 40, 40); g.restore(); // rotated and scaled up
g.save(); g.translate(60, 118); g.scale(1.7, 0.45); g.drawImage(s2, 0, 0, 200, 200, 0, -20, 30, 30); g.restore(); // scaled by a transform
put("c2d.scale." + name + ".getImageData", g.getImageData(0, 0, 220, 130).data, 220);
put("c2d.scale." + name + ".png", c.toDataURL());
}
});
// Text filled and stroked with gradients of the three kinds, with a shadow and with a global alpha: the paths the canvas takes for a gradient
// over glyphs.
await scene("c2d.gradtext", async () => {
const [c, g] = c2d(420, 210);
g.fillStyle = "#fff"; g.fillRect(0, 0, 420, 210);
const lin = g.createLinearGradient(10, 0, 400, 0);
lin.addColorStop(0, "#d00"); lin.addColorStop(0.4, "#fc0"); lin.addColorStop(0.7, "rgba(0,160,60,.6)"); lin.addColorStop(1, "#04d");
const rad = g.createRadialGradient(100, 90, 4, 130, 100, 90);
rad.addColorStop(0, "#fff"); rad.addColorStop(0.5, "#c0c"); rad.addColorStop(1, "#036");
const rad2 = g.createRadialGradient(300, 60, 30, 340, 80, 8); // the focal circle outside the start circle
rad2.addColorStop(0, "#f60"); rad2.addColorStop(1, "#0af");
const con = g.createConicGradient ? g.createConicGradient(0.6, 210, 150) : lin;
con.addColorStop(0, "#f80"); con.addColorStop(0.33, "#0c8"); con.addColorStop(0.66, "#80f"); con.addColorStop(1, "#f80");
g.textBaseline = "alphabetic";
g.font = "bold 40px sans-serif"; g.fillStyle = lin; g.fillText("Gradient 0123", 10, 44);
g.font = "italic 34px serif"; g.fillStyle = rad; g.fillText("Hamburgefonstiv", 10, 90);
g.font = "28px monospace"; g.fillStyle = rad2; g.fillText("radial focal 1/2", 220, 40);
g.font = "bold 44px Arial"; g.strokeStyle = lin; g.lineWidth = 2.5; g.strokeText("Stroke", 10, 140);
g.font = "36px 'Times New Roman'"; g.fillStyle = con; g.fillText("Conic text", 150, 150);
g.save(); g.shadowColor = "rgba(0,0,0,.55)"; g.shadowBlur = 4; g.shadowOffsetX = 2; g.shadowOffsetY = 3; g.globalAlpha = 0.8;
g.font = "30px 'Segoe UI'"; g.fillStyle = lin; g.fillText("Shadow and alpha", 10, 190); g.restore();
g.font = "20px sans-serif"; g.fillStyle = con; g.fillRect(300, 150, 110, 50); g.fillStyle = "#fff"; g.fillText("on conic", 310, 180);
put("c2d.gradtext.getImageData", g.getImageData(0, 0, 420, 210).data, 420);
put("c2d.gradtext.png", c.toDataURL());
});
// ------------------------------------------------------------------------------------------------------------ WebGL
const P1 = ["VERSION", "SHADING_LANGUAGE_VERSION", "VENDOR", "RENDERER", "MAX_TEXTURE_SIZE", "MAX_CUBE_MAP_TEXTURE_SIZE", "MAX_RENDERBUFFER_SIZE",
"MAX_VIEWPORT_DIMS", "ALIASED_LINE_WIDTH_RANGE", "ALIASED_POINT_SIZE_RANGE", "MAX_VERTEX_ATTRIBS", "MAX_VARYING_VECTORS",
"MAX_COMBINED_TEXTURE_IMAGE_UNITS", "MAX_VERTEX_TEXTURE_IMAGE_UNITS", "MAX_TEXTURE_IMAGE_UNITS", "MAX_VERTEX_UNIFORM_VECTORS",
"MAX_FRAGMENT_UNIFORM_VECTORS", "RED_BITS", "GREEN_BITS", "BLUE_BITS", "ALPHA_BITS", "DEPTH_BITS", "STENCIL_BITS", "SAMPLES",
"SAMPLE_BUFFERS", "SUBPIXEL_BITS"];
const P2 = ["MAX_3D_TEXTURE_SIZE", "MAX_ARRAY_TEXTURE_LAYERS", "MAX_COLOR_ATTACHMENTS", "MAX_DRAW_BUFFERS", "MAX_ELEMENTS_INDICES", "MAX_ELEMENTS_VERTICES",
"MAX_FRAGMENT_INPUT_COMPONENTS", "MAX_FRAGMENT_UNIFORM_BLOCKS", "MAX_FRAGMENT_UNIFORM_COMPONENTS", "MAX_PROGRAM_TEXEL_OFFSET", "MAX_SAMPLES",
"MAX_SERVER_WAIT_TIMEOUT", "MAX_TEXTURE_LOD_BIAS", "MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS", "MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS",
"MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS", "MAX_UNIFORM_BLOCK_SIZE", "MAX_UNIFORM_BUFFER_BINDINGS", "MAX_VARYING_COMPONENTS",
"MAX_VERTEX_OUTPUT_COMPONENTS", "MAX_VERTEX_UNIFORM_BLOCKS", "MAX_VERTEX_UNIFORM_COMPONENTS", "MIN_PROGRAM_TEXEL_OFFSET",
"MAX_COMBINED_UNIFORM_BLOCKS", "MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS", "MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS", "UNIFORM_BUFFER_OFFSET_ALIGNMENT"];
function glInfo(p, gl, v2) {
const params = {};
for (const n of P1.concat(v2 ? P2 : [])) {
try { let v = gl.getParameter(gl[n]); if (ArrayBuffer.isView(v)) v = Array.from(v); params[n] = v; } catch (e) { params[n] = "ERR " + e.message; }
}
put(p + ".params", params);
const exts = gl.getSupportedExtensions() || [];
put(p + ".extensions", exts);
const eo = [];
for (const e of exts) {
try { const o = gl.getExtension(e); eo.push([e, o ? Object.keys(Object.getPrototypeOf(o)).length : -1]); } catch (er) { eo.push([e, "ERR"]); }
}
put(p + ".extension_objects", eo);
const dbg = gl.getExtension("WEBGL_debug_renderer_info");
put(p + ".unmasked", dbg ? [gl.getParameter(dbg.UNMASKED_VENDOR_WEBGL), gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL)] : "no WEBGL_debug_renderer_info");
const an = gl.getExtension("EXT_texture_filter_anisotropic");
put(p + ".anisotropy", an ? gl.getParameter(an.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : "none");
const prec = [];
for (const sh of ["VERTEX_SHADER", "FRAGMENT_SHADER"]) for (const lv of ["LOW_FLOAT", "MEDIUM_FLOAT", "HIGH_FLOAT", "LOW_INT", "MEDIUM_INT", "HIGH_INT"]) {
const f = gl.getShaderPrecisionFormat(gl[sh], gl[lv]);
prec.push([sh, lv, f && f.rangeMin, f && f.rangeMax, f && f.precision]);
}
put(p + ".precision", prec);
put(p + ".attributes", gl.getContextAttributes());
}
function program(gl, vs, fs) {
const mk = (type, src) => {
const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error("shader: " + gl.getShaderInfoLog(s));
return s;
};
const pr = gl.createProgram();
gl.attachShader(pr, mk(gl.VERTEX_SHADER, vs)); gl.attachShader(pr, mk(gl.FRAGMENT_SHADER, fs));
gl.bindAttribLocation(pr, 0, "p"); gl.bindAttribLocation(pr, 1, "c");
gl.linkProgram(pr);
if (!gl.getProgramParameter(pr, gl.LINK_STATUS)) throw new Error("link: " + gl.getProgramInfoLog(pr));
gl.useProgram(pr);
return pr;
}
function buffer(gl, loc, data, size) {
const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW);
gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 0, 0);
return b;
}
function pixels(gl, w, h) { const u = new Uint8Array(w * h * 4); gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, u); return u; }
const VS = "attribute vec2 p; attribute vec4 c; varying vec4 v; varying vec2 uv; void main(){ v=c; uv=p*0.5+0.5; gl_Position=vec4(p,0.,1.); gl_PointSize=7.5; }";
const FS_COLOR = "precision mediump float; varying vec4 v; void main(){ gl_FragColor=v; }";
const QUAD = [-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1];
async function glScenes(p, v2) {
const kind = v2 ? "webgl2" : "webgl";
const mkctx = (w, h, attrs) => {
const c = document.createElement("canvas"); c.width = w; c.height = h;
return [c, c.getContext(kind, Object.assign({ preserveDrawingBuffer: true }, attrs || {}))];
};
let [c0, gl0] = mkctx(64, 64);
if (!gl0) { put(p + ".context", "null"); return; }
glInfo(p, gl0, v2);
await scene(p + ".triangle", async () => {
const [c, gl] = mkctx(96, 96, { antialias: false });
gl.viewport(0, 0, 96, 96); gl.clearColor(0.1, 0.2, 0.3, 0.4); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 0, [-0.8, -0.7, 0.9, -0.5, -0.1, 0.85], 2);
buffer(gl, 1, [1, 0, 0, 1, 0, 1, 0, 0.7, 0, 0, 1, 0.3], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
put(p + ".triangle.readPixels", pixels(gl, 96, 96), 96);
put(p + ".triangle.toDataURL", c.toDataURL());
put(p + ".triangle.toDataURL_jpeg", c.toDataURL("image/jpeg", 0.8));
const [d, g2] = c2d(96, 96); g2.drawImage(c, 0, 0);
put(p + ".triangle.drawImage", g2.getImageData(0, 0, 96, 96).data, 96);
});
await scene(p + ".antialias", async () => {
for (const aa of [true, false]) {
const [c, gl] = mkctx(96, 96, { antialias: aa });
gl.viewport(0, 0, 96, 96); gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 0, [-0.83, -0.71, 0.77, -0.43, -0.1, 0.89, 0.3, 0.9, 0.9, 0.2, 0.6, 0.95], 2);
buffer(gl, 1, [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0.8, 0, 0, 1, 0.8, 0, 0, 1, 0.8, 0, 0, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 6);
put(p + ".antialias." + aa + ".samples", gl.getParameter(gl.SAMPLES));
put(p + ".antialias." + aa + ".readPixels", pixels(gl, 96, 96), 96);
}
});
for (const prec of ["highp", "mediump"]) await scene(p + ".math." + prec, async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
const fp = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT);
const use = prec === "highp" && !(fp && fp.precision) ? "mediump" : prec;
gl.viewport(0, 0, 64, 64);
program(gl, VS, "precision " + use + " float; varying vec2 uv;" +
"void main(){ float x=uv.x*6.0; gl_FragColor=vec4(fract(sin(x)*43758.5453), fract(exp(uv.y*3.0)), fract(pow(uv.x+0.5, 2.2+uv.y)), fract(sqrt(uv.x*uv.y)*17.0)); }");
buffer(gl, 0, QUAD, 2); gl.drawArrays(gl.TRIANGLES, 0, 6);
put(p + ".math." + prec + ".readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".texture", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
gl.viewport(0, 0, 64, 64);
program(gl, VS, "precision mediump float; varying vec2 uv; uniform sampler2D t; void main(){ gl_FragColor=texture2D(t, uv*0.9+0.03); }");
const tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex);
const d = new Uint8Array(32 * 32 * 4); let s = 12345;
for (let i = 0; i < d.length; i++) { s = (s * 1103515245 + 12345) & 0x7fffffff; d[i] = (s >> 16) & 255; }
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 32, 32, 0, gl.RGBA, gl.UNSIGNED_BYTE, d);
gl.generateMipmap(gl.TEXTURE_2D);
for (const [name, mag, min] of [["linear", gl.LINEAR, gl.LINEAR], ["mip", gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR], ["nearest", gl.NEAREST, gl.NEAREST]]) {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, mag); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, min);
gl.clear(gl.COLOR_BUFFER_BIT);
buffer(gl, 0, QUAD, 2); gl.drawArrays(gl.TRIANGLES, 0, 6);
put(p + ".texture." + name + ".readPixels", pixels(gl, 64, 64), 64);
}
});
await scene(p + ".blend", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false, premultipliedAlpha: false });
gl.viewport(0, 0, 64, 64); gl.clearColor(0.2, 0.4, 0.6, 0.5); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR); gl.enable(gl.BLEND);
for (const [src, dst] of [[gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA], [gl.ONE, gl.ONE_MINUS_SRC_ALPHA], [gl.DST_COLOR, gl.ZERO]]) {
gl.blendFunc(src, dst);
buffer(gl, 0, [-0.9, -0.9, 0.3, -0.5, -0.3, 0.7], 2);
buffer(gl, 1, [0.9, 0.2, 0.1, 0.37, 0.1, 0.8, 0.3, 0.55, 0.2, 0.3, 0.9, 0.21], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
}
put(p + ".blend.readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".lines_points", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
gl.viewport(0, 0, 64, 64); gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 1, [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], 4);
buffer(gl, 0, [-0.9, -0.3, 0.9, 0.5, -0.9, 0.6, 0.2, -0.9], 2);
gl.lineWidth(1); gl.drawArrays(gl.LINES, 0, 4);
gl.lineWidth(3); buffer(gl, 0, [-0.6, -0.8, 0.8, 0.9], 2); gl.drawArrays(gl.LINES, 0, 2);
buffer(gl, 0, [-0.5, 0.5, 0.4, -0.2], 2); gl.drawArrays(gl.POINTS, 0, 2);
put(p + ".lines_points.readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".depth_stencil", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false, depth: true, stencil: true });
gl.viewport(0, 0, 64, 64); gl.clearColor(0, 0, 0, 1); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
program(gl, "attribute vec3 p; attribute vec4 c; varying vec4 v; void main(){ v=c; gl_Position=vec4(p,1.); }", FS_COLOR);
gl.enable(gl.DEPTH_TEST); gl.enable(gl.STENCIL_TEST); gl.stencilFunc(gl.ALWAYS, 1, 255); gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
buffer(gl, 0, [-0.9, -0.9, 0.2, 0.9, -0.5, -0.4, 0.0, 0.9, 0.6], 3);
buffer(gl, 1, [1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
buffer(gl, 0, [-0.9, 0.9, 0.0, 0.9, 0.9, 0.0, 0.0, -0.9, 0.5], 3);
buffer(gl, 1, [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
put(p + ".depth_stencil.readPixels", pixels(gl, 64, 64), 64);
});
if (v2) {
await scene(p + ".msaa_resolve", async () => {
const [c, gl] = mkctx(64, 64, { antialias: false });
const rb = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, rb);
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, 64, 64);
const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, rb);
const tx = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tx);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 64, 64, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
const fb2 = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb2);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tx, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, fb); gl.viewport(0, 0, 64, 64); gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
program(gl, VS, FS_COLOR);
buffer(gl, 0, [-0.83, -0.71, 0.77, -0.43, -0.1, 0.89], 2);
buffer(gl, 1, [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], 4);
gl.drawArrays(gl.TRIANGLES, 0, 3);
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fb); gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, fb2);
gl.blitFramebuffer(0, 0, 64, 64, 0, 0, 64, 64, gl.COLOR_BUFFER_BIT, gl.NEAREST);
gl.bindFramebuffer(gl.FRAMEBUFFER, fb2);
put(p + ".msaa_resolve.readPixels", pixels(gl, 64, 64), 64);
});
await scene(p + ".float_target", async () => {
const [c, gl] = mkctx(32, 32, { antialias: false });
if (!gl.getExtension("EXT_color_buffer_float")) { put(p + ".float_target", "no EXT_color_buffer_float"); return; }
const tx = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tx);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, 32, 32, 0, gl.RGBA, gl.FLOAT, null);
const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tx, 0);
gl.viewport(0, 0, 32, 32);
program(gl, VS, "precision highp float; varying vec2 uv; void main(){ gl_FragColor=vec4(sin(uv.x*9.0)*exp(uv.y), pow(uv.x+0.1, 1.7), sqrt(uv.y), uv.x/(uv.y+0.37)); }");
buffer(gl, 0, QUAD, 2); gl.drawArrays(gl.TRIANGLES, 0, 6);
const f = new Float32Array(32 * 32 * 4); gl.readPixels(0, 0, 32, 32, gl.RGBA, gl.FLOAT, f);
put(p + ".float_target.readPixels", f, 32);
});
}
}
await scene("gl1", () => glScenes("gl1", false));
await scene("gl2", () => glScenes("gl2", true));
await scene("worker.webgl", async () => {
if (typeof Worker === "undefined" || typeof OffscreenCanvas === "undefined") { put("worker.webgl", "no worker or OffscreenCanvas"); return; }
const src = "onmessage = () => { try { const c = new OffscreenCanvas(32, 32), gl = c.getContext('webgl'); if (!gl) { postMessage({err: 'no webgl'}); return; }" +
"const d = gl.getExtension('WEBGL_debug_renderer_info');" +
"gl.clearColor(0.25, 0.5, 0.75, 1); gl.clear(gl.COLOR_BUFFER_BIT); const u = new Uint8Array(32*32*4); gl.readPixels(0,0,32,32,gl.RGBA,gl.UNSIGNED_BYTE,u);" +
"postMessage({vendor: gl.getParameter(gl.VENDOR), renderer: gl.getParameter(gl.RENDERER), unmasked: d ? [gl.getParameter(d.UNMASKED_VENDOR_WEBGL), gl.getParameter(d.UNMASKED_RENDERER_WEBGL)] : null," +
"exts: gl.getSupportedExtensions(), px: Array.from(u.subarray(0, 16))}); } catch (e) { postMessage({err: String(e)}); } };";
const w = new Worker(URL.createObjectURL(new Blob([src])));
const r = await Promise.race([new Promise((res) => { w.onmessage = (e) => res(e.data); w.onerror = (e) => res({ err: "worker error " + e.message }); w.postMessage(1); }),
sleep(10000).then(() => ({ err: "timeout" }))]);
w.terminate();
put("worker.webgl", r);
});
await scene("gpu.webgpu", async () => {
if (!navigator.gpu) { put("gpu.webgpu", "no navigator.gpu"); return; }
const a = await Promise.race([navigator.gpu.requestAdapter(), sleep(10000).then(() => "timeout")]);
if (!a || a === "timeout") { put("gpu.webgpu", String(a)); return; }
const info = a.info || (a.requestAdapterInfo ? await a.requestAdapterInfo() : {});
// Features and limits are read by NAME, never by iterating them: the expression runs with the page's objects behind Xray wrappers, and
// `Array.from(a.features)` / `for (k in a.limits)` threw "Xray wrapping of iterators not supported" there (run 43652292533). `has` and a property
// read are plain calls. The names are those of the WebGPU specification (limits table and GPUFeatureName); one the engine does not know reads
// false / undefined, which is a value like any other.
const featureNames = ["depth-clip-control", "depth32float-stencil8", "texture-compression-bc", "texture-compression-bc-sliced-3d",
"texture-compression-etc2", "texture-compression-astc", "texture-compression-astc-sliced-3d", "timestamp-query", "indirect-first-instance",
"shader-f16", "rg11b10ufloat-renderable", "bgra8unorm-storage", "float32-filterable", "float32-blendable", "clip-distances",
"dual-source-blending", "subgroups"];
const limitNames = ["maxTextureDimension1D", "maxTextureDimension2D", "maxTextureDimension3D", "maxTextureArrayLayers", "maxBindGroups",
"maxBindGroupsPlusVertexBuffers", "maxBindingsPerBindGroup", "maxDynamicUniformBuffersPerPipelineLayout",
"maxDynamicStorageBuffersPerPipelineLayout", "maxSampledTexturesPerShaderStage", "maxSamplersPerShaderStage",
"maxStorageBuffersPerShaderStage", "maxStorageTexturesPerShaderStage", "maxUniformBuffersPerShaderStage", "maxUniformBufferBindingSize",
"maxStorageBufferBindingSize", "minUniformBufferOffsetAlignment", "minStorageBufferOffsetAlignment", "maxVertexBuffers", "maxBufferSize",
"maxVertexAttributes", "maxVertexBufferArrayStride", "maxInterStageShaderVariables", "maxColorAttachments",
"maxColorAttachmentBytesPerSample", "maxComputeWorkgroupStorageSize", "maxComputeInvocationsPerWorkgroup", "maxComputeWorkgroupSizeX",
"maxComputeWorkgroupSizeY", "maxComputeWorkgroupSizeZ", "maxComputeWorkgroupsPerDimension"];
const lim = {}, feat = {};
for (const k of limitNames) { try { lim[k] = a.limits[k]; } catch (e) { lim[k] = "ERR " + e.message; } }
for (const f of featureNames) { try { feat[f] = a.features.has(f); } catch (e) { feat[f] = "ERR " + e.message; } }
put("gpu.webgpu.info", { vendor: info.vendor, architecture: info.architecture, device: info.device, description: info.description });
put("gpu.webgpu.features", feat);
put("gpu.webgpu.limits", lim);
});
// ------------------------------------------------------------------------------------------------------------ DOM text
await scene("dom.text", async () => {
const box = document.createElement("div"); box.style.cssText = "position:absolute;left:0;top:0;white-space:nowrap";
document.body.appendChild(box);
const rows = [];
for (const f of FONTS) for (const t of TEXTS) {
const s = document.createElement("span"); s.style.font = f; s.textContent = t; box.appendChild(s);
const r = s.getBoundingClientRect();
rows.push([f, t, r.width, r.height, s.offsetWidth, s.offsetHeight]);
box.removeChild(s);
}
put("dom.span_boxes", rows);
const para = [];
for (const f of ["16px sans-serif", "15px 'Times New Roman'", "14px Consolas"]) {
const d = document.createElement("div"); d.style.cssText = "width:200px;font:" + f; d.textContent = TEXTS.join(" · ") + " " + TEXTS.join(" · ");
box.appendChild(d); const r = d.getBoundingClientRect(); para.push([f, r.width, r.height]); box.removeChild(d);
}
put("dom.paragraphs", para);
put("dom.fonts_check", FONTS.map((f) => [f, document.fonts.check(f)]));
const colors = ["Canvas", "CanvasText", "ButtonFace", "ButtonText", "ButtonBorder", "Field", "FieldText", "Highlight", "HighlightText", "GrayText", "LinkText",
"VisitedText", "ActiveText", "Mark", "MarkText", "AccentColor", "AccentColorText", "SelectedItem", "SelectedItemText"];
put("dom.system_colors", colors.map((c) => { const e = document.createElement("i"); e.style.color = c; box.appendChild(e); const v = getComputedStyle(e).color; box.removeChild(e); return [c, v]; }));
document.body.removeChild(box);
});
return out;
})()
@@ -0,0 +1,31 @@
"""`context.add_init_script` added after a page exists runs once in each document, not twice.
The context-level script was registered on both sides: in the browser (`Browser.setInitScripts`, which the engine applies to every
page of the context, the ones already open included) and, for the pages already open, again in each page's own list. A page that
existed when the script was added ran it twice in every later document; a page opened afterwards ran it once, so the test that adds the
script first passed. Playwright runs a context script once in each document of each page.
"""
from __future__ import annotations
import pytest
pytestmark = pytest.mark.e2e
PAGE = ("<!doctype html><title>t</title><script>window.__seen = JSON.stringify(window.__o || []);</script>")
def test_a_context_script_added_after_the_page_exists_runs_once(firefox_binary, tmp_path):
from invisible_playwright import InvisiblePlaywright
(tmp_path / "p.html").write_text(PAGE, encoding="utf-8")
url = (tmp_path / "p.html").as_uri()
with InvisiblePlaywright(seed=4261, binary_path=firefox_binary, headless=True) as browser:
context = browser.new_context()
existing = context.new_page() # the page exists BEFORE the script
context.add_init_script("(window.__o = window.__o || []).push('init');")
later = context.new_page() # and a page opened AFTER it
for page in (existing, later):
page.goto(url, wait_until="load")
assert page.evaluate("window.__o") == ["init"], "the script ran %r" % page.evaluate("window.__o")
page.goto(url + "?again", wait_until="load") # the next document of the same page, too
assert page.evaluate("window.__o") == ["init"], "the second document ran %r" % page.evaluate("window.__o")
@@ -0,0 +1,99 @@
"""A CORS preflight is not a request the client hears of, as on stock Firefox.
A page at one origin fetches another origin with a header that needs a preflight: the browser sends an OPTIONS request first. Playwright's
own server drops an OPTIONS request that no route holds before the client can see it (ffNetworkManager `_onRequestWillBeSent`);
ours reported it, so a page with preflighted fetches showed more requests than on stock (measured on cnbc.com and scmp.com: 10 and
18 OPTIONS requests a page, none on stock). The test counts what the client hears: the document and the two fetches, no OPTIONS, with
and without a context route (a route that holds the request is another story and keeps it).
"""
from __future__ import annotations
import threading
from http.server import BaseHTTPRequestHandler
import pytest
from _servers import LocalServer
pytestmark = pytest.mark.e2e
class _Api(BaseHTTPRequestHandler):
hits: list = []
def log_message(self, *a):
pass
def _cors(self):
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Headers", "x-test")
self.send_header("Access-Control-Allow-Methods", "GET, OPTIONS")
def do_OPTIONS(self):
_Api.hits.append(("OPTIONS", self.path))
self.send_response(204)
self._cors()
self.end_headers()
def do_GET(self):
_Api.hits.append(("GET", self.path))
body = b'{"ok":1}'
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self._cors()
self.end_headers()
self.wfile.write(body)
def _page(api_origin):
return ("<!doctype html><title>preflight</title><script>"
"fetch('%s/one', {headers: {'x-test': '1'}}); fetch('%s/two', {headers: {'x-test': '2'}});"
"</script>" % (api_origin, api_origin)).encode()
@pytest.fixture
def two_origins():
_Api.hits = []
class Page(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
body = _page(self.server.api_origin)
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
api = LocalServer(("127.0.0.1", 0), _Api)
page = LocalServer(("127.0.0.1", 0), Page)
page.api_origin = "http://localhost:%d" % api.server_address[1]
for srv in (api, page):
threading.Thread(target=srv.serve_forever, daemon=True).start()
try:
yield "http://127.0.0.1:%d/" % page.server_address[1]
finally:
for srv in (api, page):
srv.shutdown()
srv.server_close()
@pytest.mark.parametrize("route", [False, True])
def test_the_client_hears_the_document_and_the_fetches_and_no_preflight(firefox_binary, two_origins, route):
from invisible_playwright import InvisiblePlaywright
heard = []
with InvisiblePlaywright(seed=4261, binary_path=firefox_binary, headless=True) as browser:
context = browser.new_context()
if route:
context.route("**/*", lambda r: r.continue_())
page = context.new_page()
page.on("request", lambda r: heard.append((r.method, r.url.rsplit("/", 1)[-1] or "page")))
page.goto(two_origins, wait_until="load")
page.wait_for_timeout(2000) # the events of a sync client are delivered while it calls the browser
assert ("OPTIONS", "/one") in _Api.hits or ("OPTIONS", "/two") in _Api.hits, "the browser made no preflight: %r" % _Api.hits
methods = sorted(m for m, _ in heard)
assert methods == ["GET", "GET", "GET"], "the client heard %r (the server saw %r)" % (heard, _Api.hits)
@@ -11,9 +11,9 @@ from pathlib import Path
TESTS = str(Path(__file__).resolve().parent)
_BUILD = """
from invisible_playwright._juggler.server import _ThreadStarter
from invisible_playwright._juggler._threads import ThreadStarter
def build():
return _ThreadStarter(on_error=lambda message: None)
return ThreadStarter(on_error=lambda message: None)
"""
@@ -81,3 +81,29 @@ def test_a_browser_shared_by_the_tests_of_a_module_may_stay_open_until_the_modul
out = done.stdout + done.stderr
assert done.returncode == 0, out
assert "2 passed" in out, out
def test_the_census_counts_a_starter_whose_thread_has_not_begun(monkeypatch):
"""The starter's thread is begun without waiting for it, so right after the constructor it can be in no `threading.enumerate()`:
the census must still count it (it missed both leaks of a module on a Linux runner, 3 of 3 jobs)."""
import threading
import time
sys.path.insert(0, TESTS)
import _browser_census as census
from invisible_playwright._juggler._threads import ThreadStarter
original = threading.Thread.start
def slow_start(self):
time.sleep(0.3)
return original(self)
monkeypatch.setattr(threading.Thread, "start", slow_start)
before = len(census.starters_alive())
starter = ThreadStarter(on_error=lambda message: None)
try:
assert len(census.starters_alive()) == before + 1
finally:
starter.stop()
assert census.wait_until_back_to(before) == 0
@@ -77,12 +77,16 @@ class _Page:
def test_a_page_the_engine_answers_after_35_s_is_still_a_page(monkeypatch):
monkeypatch.setattr(srv, "PageDispatcher", _Page)
engine = _SlowEngine()
browser = BrowserDispatcher(Server(), None, engine, "151.0", session_seed=1)
server = Server()
browser = BrowserDispatcher(server, None, engine, "151.0", session_seed=1)
engine.browser = browser
context = BrowserContextDispatcher(browser.server, browser, {}, "C1")
browser.contexts.append(context)
result = context.op_new_page({"pageNumber": 0})
try:
result = context.op_new_page({"pageNumber": 0})
finally:
server.shutdown() # the connection's one starter ends with its server
assert result == {"page": {"guid": "page-T0"}}
assert engine.bounds == [None], (
@@ -0,0 +1,122 @@
"""`InProcessTransport.connect` returns without waiting for any thread to start.
`connect` is a coroutine of the user's event loop, and `Thread.start` does not return until the new thread is running. Measured with
four browsers in one process under CPU load on Windows, the four worker starts held the loop ~200 ms per launch (4.4% of the main
thread's wall time). The workers are now started by a bootstrapper that is not the loop (and is itself begun without a
`Thread.start`), and a message sent right after `connect` waits in the queue until a worker runs.
NO BROWSER HERE: a scripted server behind the real transport, with `Thread.start` slowed to 300 ms, the way a loaded machine slows it.
Known-bad input: workers started inside `connect` -> `connect` takes 4 x 300 ms and fails the 50 ms bound.
"""
from __future__ import annotations
import asyncio
import threading
import time
import pytest
from invisible_playwright._juggler.dispatcher import Server
from invisible_playwright._juggler.transport import InProcessTransport
pytestmark = pytest.mark.unit
START_DELAY_S = 0.3
class _Server(Server):
"""The registry's base class, whose `thread_starter` the transport starts its workers through, answering every call with its id."""
def handle(self, message):
return {"echo": message["id"]}
def test_connect_returns_before_any_worker_has_started_and_a_message_is_still_answered(monkeypatch):
original = threading.Thread.start
def slow_start(self):
time.sleep(START_DELAY_S)
return original(self)
monkeypatch.setattr(threading.Thread, "start", slow_start)
async def scenario():
loop = asyncio.get_running_loop()
transport = InProcessTransport(loop, _Server())
replies: "asyncio.Queue" = asyncio.Queue()
transport.on_message = replies.put_nowait
began = time.perf_counter()
await transport.connect()
took = time.perf_counter() - began
transport.send({"id": 7, "guid": "g", "method": "m", "params": {}})
reply = await asyncio.wait_for(replies.get(), 10)
transport.request_stop()
await asyncio.wait_for(transport.wait_until_stopped(), 10)
return took, reply
took, reply = asyncio.run(scenario())
assert took < 0.05, "connect() waited %.0f ms: a thread was started on the loop" % (took * 1000)
assert reply == {"id": 7, "result": {"echo": 7}}
def test_a_transport_stopped_before_its_workers_started_ends_without_error(monkeypatch):
original = threading.Thread.start
def slow_start(self):
time.sleep(START_DELAY_S)
return original(self)
monkeypatch.setattr(threading.Thread, "start", slow_start)
async def scenario():
transport = InProcessTransport(asyncio.get_running_loop(), _Server())
await transport.connect()
transport.request_stop()
await asyncio.wait_for(transport.wait_until_stopped(), 10)
asyncio.run(scenario())
def test_building_the_shared_starter_waits_for_no_thread_start(monkeypatch):
"""The starter every caller of `ThreadStarter` builds on its own thread must not itself cost a `Thread.start` there."""
from invisible_playwright._juggler._threads import ThreadStarter
original = threading.Thread.start
def slow_start(self):
time.sleep(START_DELAY_S)
return original(self)
monkeypatch.setattr(threading.Thread, "start", slow_start)
began = time.perf_counter()
starter = ThreadStarter(on_error=lambda why: None)
ran = threading.Event()
starter.start(target=ran.set, name="invpw-test-started")
took = time.perf_counter() - began
try:
assert took < 0.05, "building the starter and queueing a thread waited %.0f ms" % (took * 1000)
assert ran.wait(10), "the queued thread never ran"
finally:
starter.stop()
def test_a_browsers_reader_and_the_transports_workers_share_ONE_starter():
"""Each browser costs one starter thread, not two: the transport's workers and the browser's lease both go through the server's."""
from invisible_playwright._juggler._threads import ThreadStarter, ThreadStarterLease
async def scenario():
server = _Server()
transport = InProcessTransport(asyncio.get_running_loop(), server)
before = len(ThreadStarter.open_starters())
await transport.connect()
lease = ThreadStarterLease(lambda: server.thread_starter)
ran = threading.Event()
lease.start(target=ran.set, name="invpw-test-started")
assert ran.wait(10)
opened = len(ThreadStarter.open_starters()) - before
transport.request_stop()
await asyncio.wait_for(transport.wait_until_stopped(), 10)
return opened
assert asyncio.run(scenario()) == 1
+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.
+109
View File
@@ -0,0 +1,109 @@
"""`Locator.screenshot()` / `ElementHandle.screenshot()` photograph the element: its size, its pixels, wherever it is.
The wrapper had no `screenshot` on an element handle ("ElementHandle has no method 'screenshot'"). The picture is the page's own
screenshot of the element's box, so the checks are the ones that can go wrong with a box: an element below the fold (it has to be
scrolled in and the document scroll added to a box that is in viewport coordinates), an element inside a frame that the page has
scrolled, an `<iframe>` element itself, and the size of the picture being the size of the box.
"""
from __future__ import annotations
import struct
import zlib
import pytest
pytestmark = pytest.mark.e2e
GREEN, PINK = (0, 204, 68), (255, 0, 170)
PAGE = (
"<!doctype html><title>shot</title><body style='margin:0;background:#fff'>"
"<div id='top' style='position:absolute;left:20px;top:10px;width:30px;height:20px;background:#ff00aa'></div>"
"<div id='below' style='position:absolute;left:40px;top:2500px;width:80px;height:60px;background:#00cc44'></div>"
"<iframe id='f' style='position:absolute;left:100px;top:900px;width:200px;height:120px;border:0' srcdoc=\""
"<body style='margin:0;background:#ff00aa'><div style='height:600px'></div>"
"<div id='inner' style='margin-left:15px;width:50px;height:40px;background:#00cc44'></div>"
"<div style='height:900px'></div>\"></iframe>"
"<div style='position:absolute;top:4000px;width:1px;height:1px'></div>"
)
def decode_png(data: bytes):
"""(width, height, pixel(x, y)) of an 8-bit RGB/RGBA PNG without interlacing."""
assert data[:8] == b"\x89PNG\r\n\x1a\n", "not a PNG"
pos, idat, width = 8, b"", 0
while pos < len(data):
length, kind = struct.unpack(">I4s", data[pos:pos + 8])
body = data[pos + 8:pos + 8 + length]
if kind == b"IHDR":
width, height, depth, color, _c, _f, interlace = struct.unpack(">IIBBBBB", body)
assert depth == 8 and color in (2, 6) and interlace == 0, (depth, color, interlace)
step = 3 if color == 2 else 4
elif kind == b"IDAT":
idat += body
pos += 12 + length
raw, stride, rows, prev = zlib.decompress(idat), width * step, [], bytearray(width * step)
for y in range(height):
ft, line = raw[y * (stride + 1)], bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)])
for i in range(stride):
a = line[i - step] if i >= step else 0
b = prev[i]
c = prev[i - step] if i >= step else 0
if ft == 1:
line[i] = (line[i] + a) & 255
elif ft == 2:
line[i] = (line[i] + b) & 255
elif ft == 3:
line[i] = (line[i] + (a + b) // 2) & 255
elif ft == 4:
p = a + b - c
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 255
rows.append(line)
prev = line
return width, height, lambda x, y: tuple(rows[y][x * step:x * step + 3])
def _near(a, b, tol=6):
return all(abs(p - q) <= tol for p, q in zip(a, b))
def _whole(png, color):
width, height, pixel = decode_png(png)
for x, y in ((0, 0), (width - 1, 0), (0, height - 1), (width - 1, height - 1), (width // 2, height // 2)):
assert _near(pixel(x, y), color), ((x, y), pixel(x, y), color)
return width, height
def test_an_element_screenshot_is_the_element_wherever_it_is(firefox_binary, tmp_path):
from invisible_playwright import InvisiblePlaywright
(tmp_path / "p.html").write_text(PAGE, encoding="utf-8")
with InvisiblePlaywright(seed=4262, binary_path=firefox_binary, headless=True) as browser:
page = browser.new_context().new_page()
page.goto((tmp_path / "p.html").as_uri(), wait_until="load")
# in view
assert _whole(page.locator("#top").screenshot(scale="css"), PINK) == (30, 20)
# far below the fold: scrolled in, then the document scroll is added to its viewport box
assert page.evaluate("window.scrollY") == 0
assert _whole(page.locator("#below").screenshot(scale="css"), GREEN) == (80, 60)
# the same element again, now that the page has scrolled to it
assert _whole(page.locator("#below").screenshot(scale="css"), GREEN) == (80, 60)
# an element in a frame, below that frame's fold, in a page that is scrolled: size and pixels
frame = page.frames[1]
assert _whole(frame.locator("#inner").screenshot(scale="css"), GREEN) == (50, 40)
# the <iframe> element is the frame: pink around, the green swatch inside it
width, height, pixel = decode_png(page.locator("#f").screenshot(scale="css"))
assert (width, height) == (200, 120)
assert _near(pixel(3, 3), PINK)
def test_an_element_that_is_not_there_has_no_screenshot(firefox_binary, tmp_path):
from invisible_playwright import InvisiblePlaywright
(tmp_path / "p.html").write_text("<!doctype html><div id='gone' style='display:none'>x</div>", encoding="utf-8")
with InvisiblePlaywright(seed=4263, binary_path=firefox_binary, headless=True) as browser:
page = browser.new_context().new_page()
page.goto((tmp_path / "p.html").as_uri(), wait_until="load")
with pytest.raises(Exception, match="not visible"):
page.locator("#gone").screenshot(timeout=2000)
+283
View File
@@ -0,0 +1,283 @@
"""`page.expose_function` / `page.expose_binding` / `context.expose_function` / `context.expose_binding`.
They used to refuse ("not wired" / "no method 'exposeBinding'"). The page calls a Python function and gets its answer as a
promise: the value, a rejection when the Python function raised, an await when it is async.
THE RULE THAT MATTERS MORE THAN THE FEATURE: A PAGE SEES `foo` AND NOTHING ELSE. A page can list the names on its window, so a
transport left there is the driver's signature. These tests read what the page reads: the own properties of `window` (names and
symbols) with and without an exposed function, in the top, in a frame of another site (another process), in the document born
after a navigation and after `document.open()`; what `foo.toString()` and the stack of an error from `foo` say; and that `foo`
looks like a function the page defined itself (name, length, descriptor, own properties, position among the keys).
"""
from __future__ import annotations
import http.server
import threading
import pytest
pytestmark = pytest.mark.e2e
PAGE = "<!doctype html><title>t</title><body><iframe id='f' srcdoc='<p>frame</p>'></iframe>"
# What a page can read of its own window: every own name, own symbols, and the enumeration order.
WINDOW = ("(() => ({names: Object.getOwnPropertyNames(window).sort(), keys: Object.keys(window),"
" symbols: Object.getOwnPropertySymbols(window).map(String)}))()")
#: Words that would give the driver away, in anything the page can read.
TELLS = ("playwright", "binding", "juggler", "invisible", "chrome://", "resource://", "moz-src", "debugger eval")
@pytest.fixture
def browser(firefox_binary):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=4264, binary_path=firefox_binary, headless=True) as b:
yield b
@pytest.fixture
def url(tmp_path):
(tmp_path / "p.html").write_text(PAGE, encoding="utf-8")
return (tmp_path / "p.html").as_uri()
def _extra(seen, base):
return sorted(set(seen["names"]) - set(base["names"])), sorted(set(seen["symbols"]) - set(base["symbols"]))
def test_a_page_function_exposed_before_the_load_answers_and_survives_a_navigation(browser, url):
page = browser.new_context().new_page()
page.expose_function("add", lambda a, b: a + b)
for target in (url, url + "?again"):
page.goto(target, wait_until="load")
assert page.evaluate("add(2, 3)") == 5
def test_a_page_function_exposed_after_the_load_reaches_the_document_that_exists(browser, url):
page = browser.new_context().new_page()
page.goto(url, wait_until="load")
page.expose_function("twice", lambda x: x * 2)
assert page.evaluate("twice(21)") == 42
def test_two_functions_on_one_page_answer_each_its_own_calls(browser, url):
page = browser.new_context().new_page()
page.expose_function("one", lambda: "one")
page.expose_function("two", lambda: "two")
page.goto(url, wait_until="load")
assert page.evaluate("Promise.all([one(), two(), two(), one()])") == ["one", "two", "two", "one"]
def test_the_answer_is_awaited_and_a_python_error_rejects_the_promise(browser, url):
page = browser.new_context().new_page()
def boom(_):
raise ValueError("nope from python")
async def slow(x):
return {"got": x, "list": [1, 2]}
page.expose_function("boom", boom)
page.expose_function("slow", slow)
page.goto(url, wait_until="load")
assert page.evaluate("slow('a')") == {"got": "a", "list": [1, 2]}
assert "nope from python" in page.evaluate("boom(1).then(() => 'resolved', e => String(e.message))")
def test_a_binding_gets_the_source_page_and_frame(browser, url):
page = browser.new_context().new_page()
seen = {}
def binding(source, value):
seen.update(page=source["page"], frame=source["frame"], context=source["context"])
return value
page.expose_binding("who", binding)
page.goto(url, wait_until="load")
assert page.evaluate("who('x')") == "x"
assert seen["page"] is page and seen["frame"] is page.main_frame and seen["context"] is page.context
def test_a_page_function_is_not_on_another_page_of_the_context(browser, url):
context = browser.new_context()
first, second = context.new_page(), context.new_page()
first.expose_function("mine", lambda: "first")
first.goto(url, wait_until="load")
second.goto(url, wait_until="load")
assert first.evaluate("typeof mine") == "function"
assert second.evaluate("typeof mine") == "undefined"
def test_a_context_function_is_on_the_page_that_exists_the_page_to_come_and_their_frames(browser, url):
context = browser.new_context()
existing = context.new_page()
existing.goto(url, wait_until="load")
context.expose_function("ctx", lambda x: "ctx:" + x)
later = context.new_page()
later.goto(url, wait_until="load")
for page in (existing, later):
assert page.evaluate("ctx('a')") == "ctx:a"
frame = page.frames[1]
assert frame.evaluate("ctx('b')") == "ctx:b"
existing.goto(url + "?again", wait_until="load")
assert existing.evaluate("ctx('c')") == "ctx:c"
def test_a_disposed_function_is_gone_now_and_in_the_documents_to_come(browser, url):
page = browser.new_context().new_page()
page.goto(url, wait_until="load")
handle = page.expose_function("gone", lambda: 1)
assert page.evaluate("gone()") == 1
handle.dispose()
assert page.evaluate("typeof gone") == "undefined"
page.goto(url + "?again", wait_until="load")
assert page.evaluate("typeof gone") == "undefined"
# ── what the page can read ──────────────────────────────────────────────────────────────────────────────────────────────────
def test_without_an_exposed_function_nothing_is_added_and_with_one_only_its_name(browser, url):
"""No `expose_*`: the engine installs nothing, and the window has no name that is ours. After `expose_function('foo')` the
window has `foo` more, and no symbol more: the transport is not reachable."""
plain = browser.new_context().new_page()
plain.goto(url, wait_until="load")
base = plain.evaluate(WINDOW)
assert not [n for n in base["names"] if any(t in n.lower() for t in ("playwright", "binding", "juggler"))]
context = browser.new_context()
page = context.new_page()
context.expose_function("foo", lambda x: x)
page.goto(url, wait_until="load")
seen = page.evaluate(WINDOW)
assert _extra(seen, base) == (["foo"], [])
assert seen["keys"][: len(base["keys"])] == base["keys"], "the order of the keys moved"
assert seen["keys"][-1] == "foo"
def test_the_only_name_is_foo_in_a_frame_of_another_site_and_in_the_document_after_a_navigation(browser, tmp_path):
"""127.0.0.1 and localhost are two sites, so two processes. The frame of the other site, a nested frame, the document the
page navigates to and the one a `document.open()` rewrites: each shows `foo` and nothing else."""
class Handler(http.server.BaseHTTPRequestHandler):
pages = {}
def do_GET(self):
body = self.pages.get(self.path.split("?")[0], "<!doctype html><title>t</title>").encode()
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *_):
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
port = server.server_address[1]
Handler.pages = {
"/top": "<!doctype html><title>top</title><iframe src='http://localhost:%d/child'></iframe>" % port,
"/child": "<!doctype html><title>child</title><iframe src='http://127.0.0.1:%d/grand'></iframe>" % port,
"/grand": "<!doctype html><title>grand</title>",
}
try:
plain = browser.new_context().new_page()
plain.goto("http://127.0.0.1:%d/top" % port, wait_until="load")
plain.wait_for_function("window.frames.length >= 0")
plain.wait_for_timeout(1500)
base = {f.url: f.evaluate(WINDOW) for f in plain.frames}
assert len(base) == 3, sorted(base)
context = browser.new_context()
page = context.new_page()
context.expose_function("foo", lambda x: x)
for target in ("http://127.0.0.1:%d/top" % port, "http://127.0.0.1:%d/top?again" % port):
page.goto(target, wait_until="load")
page.wait_for_timeout(1500)
seen = {f.url.split("?")[0]: f.evaluate(WINDOW) for f in page.frames}
assert sorted(seen) == sorted(base)
for frame_url, window in seen.items():
assert _extra(window, base[frame_url]) == (["foo"], []), frame_url
# a child that reads its parent and its top finds no name of ours either
child = next(f for f in page.frames if f.url.startswith("http://localhost"))
# (cross-site: the parent is opaque to the child, which is the point; the same-origin case is the srcdoc test below)
assert child.evaluate("typeof foo") == "function"
# after document.open() the window of the document is the one it was
page.evaluate("document.open(); document.write('<!doctype html><p>again</p>'); document.close()")
after = page.evaluate(WINDOW)
assert _extra(after, base[sorted(base)[0]]) == (["foo"], []) or "foo" in after["names"]
assert not [n for n in after["names"] if any(t in n.lower() for t in ("playwright", "binding", "juggler"))]
finally:
server.shutdown()
def test_a_same_origin_child_reading_parent_and_top_finds_nothing_more_than_foo(browser, url):
plain = browser.new_context().new_page()
plain.goto(url, wait_until="load")
base = plain.evaluate(WINDOW)
context = browser.new_context()
page = context.new_page()
page.expose_function("foo", lambda x: x)
page.goto(url, wait_until="load")
child = page.frames[1]
for reach in ("parent", "top"):
seen = child.evaluate("(() => ({names: Object.getOwnPropertyNames(%s).sort(), symbols: Object.getOwnPropertySymbols(%s).length}))()"
% (reach, reach))
assert _extra({"names": seen["names"], "symbols": []}, base) == (["foo"], []), reach
assert seen["symbols"] == 0
page.evaluate("document.open(); document.write('<!doctype html><p>again</p>'); document.close()")
assert _extra(page.evaluate(WINDOW), base) == (["foo"], [])
def test_foo_reads_as_a_function_the_page_defined(browser, url):
"""Its source, its name, its length, its own properties, its descriptor on the window and its place among the keys are those of
`window.bar = function (...args) { ... }` written by the page, and nothing in what it says or in the stack of an error raised
from it names the driver."""
page = browser.new_context().new_page()
page.expose_function("foo", lambda x: x)
page.expose_function("raises", lambda x: (_ for _ in ()).throw(ValueError("python said no")))
page.goto(url, wait_until="load")
# a script tag runs in the page's own realm (an evaluate runs in the caller's, whose Function.prototype is another one)
page.add_script_tag(content="window.bar = function (...args) { return args; }")
read = page.evaluate("""(() => {
const d = n => { const x = Object.getOwnPropertyDescriptor(window, n); return {w: x.writable, e: x.enumerable, c: x.configurable, t: typeof x.value}; };
// the own properties FIRST: reading `name` or `length` resolves them and moves them in the list
const own = Object.getOwnPropertyNames(foo), ownBar = Object.getOwnPropertyNames(bar);
return {
own, ownBar, name: foo.name, length: foo.length,
desc: d('foo'), descBar: d('bar'), proto: Object.getPrototypeOf(foo) === Object.getPrototypeOf(bar),
source: foo.toString(), symbols: Object.getOwnPropertySymbols(foo).length,
keys: Object.keys(window).filter(k => k === 'foo' || k === 'bar' || k === 'raises'),
ctor: foo.constructor === bar.constructor,
};
})()""")
assert read["name"] == "foo" and read["length"] == 0
assert read["own"] == read["ownBar"]
assert read["desc"] == read["descBar"] and read["symbols"] == 0 and read["proto"] and read["ctor"]
assert read["keys"] == ["foo", "raises", "bar"], read["keys"]
assert not [t for t in TELLS if t in read["source"].lower()], read["source"]
# the stack of an error thrown by the call itself (a value that cannot be sent) and of a rejection from Python
stacks = page.evaluate("""(async () => {
const out = [];
try { await foo(1n); } catch (e) { out.push(String(e.stack), String(e.message), e.name); }
try { await raises(1); } catch (e) { out.push(String(e.stack), String(e.message), e.name); }
return out;
})()""")
assert len(stacks) == 6
for text in stacks:
assert not [t for t in TELLS if t in text.lower()], text
assert "python said no" in stacks[4]
def test_a_worker_gets_nothing(browser, url):
"""The engine installs a binding in the frames of a page, as Playwright's does: a worker has no `foo`, and its global
has nothing more than a worker of a page without one."""
page = browser.new_context().new_page()
probe = ("new Promise(r => { const w = new Worker(URL.createObjectURL(new Blob(["
"'postMessage(JSON.stringify({foo: typeof foo, names: Object.getOwnPropertyNames(self).sort()}))'])));"
" w.onmessage = e => r(JSON.parse(e.data)); })")
page.goto(url, wait_until="load")
base = page.evaluate(probe)
page.expose_function("foo", lambda: 1)
page.goto(url + "?again", wait_until="load")
seen = page.evaluate(probe)
assert seen == base and seen["foo"] == "undefined"
+35
View File
@@ -0,0 +1,35 @@
"""Exposed functions need an engine that hands the page-side end of a binding over and has `Page.addBinding`.
No fallback to a name on the window: an engine without them is refused with a sentence that says so, before anything is installed.
(No browser: the engine is read from its files.)
"""
from __future__ import annotations
import pytest
pytestmark = pytest.mark.unit
def test_an_engine_without_what_the_functions_need_refuses_and_leaves_no_name(tmp_path):
"""No fallback to a name on the window: an engine without `Page.addBinding` and the binding that hands its end over is
refused with a sentence that says so."""
from invisible_playwright._juggler import _bindings
from invisible_playwright._juggler.dispatcher import ProtocolException
from invisible_playwright._juggler.server import BrowserContextDispatcher
loose = tmp_path / "modules" / "juggler" / "protocol"
loose.mkdir(parents=True)
(loose / "Protocol.js").write_text("'addBinding': { params: {} },", encoding="utf-8")
assert _bindings.engine_supports(str(tmp_path)) is False # one addBinding: the browser's only
assert _bindings.engine_supports("") is False
(loose / "Protocol.js").write_text("'addBinding': { params: {} },\n'addBinding': { params: {} },", encoding="utf-8")
_bindings.engine_supports.cache_clear()
assert _bindings.engine_supports(str(tmp_path)) is True
class Browser:
engine_dir = str(tmp_path / "old")
context = object.__new__(BrowserContextDispatcher)
context.__dict__["browser"] = Browser()
with pytest.raises(ProtocolException, match="newer engine"):
BrowserContextDispatcher.require_binding_engine(context)
@@ -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
+1 -1
View File
@@ -189,7 +189,7 @@ def test_a_long_session_does_not_accumulate_subscribers(firefox_binary, first_ru
assert leaked_objects == 0, (
"forty open-and-close cycles left %d objects in the server's guid "
"registry; a closed page must be disposed, which is also what the "
"driver does and what diff_protocol's fifth dimension compares"
"driver does and what the old protocol comparison's fifth dimension compared"
% leaked_objects)
+2 -2
View File
@@ -92,7 +92,7 @@ def test_the_default_is_the_PYTHON_SERVER(monkeypatch):
user session into an experiment. What flipped it is four measurements taken
on one code state, not the code looking done: `run_e2e.py` 188 passed on
BOTH transports; the transport judge 50 green on both with 0 red only on
ours; `diff_protocol.py` at parity on methods, parameters, object types,
ours; the protocol comparison at parity on methods, parameters, object types,
initializer fields, events and parentage; and the realness gates green on
this path for the first time.
@@ -108,7 +108,7 @@ def test_the_driver_is_still_reachable_by_name(monkeypatch):
"""⛔ The way back has to keep working, or the flip above is one-way.
A user whose session behaves differently on the new path must be able to
say so and get the old one, and `judge_both_transports.py` needs it to have
say so and get the old one, and any comparison between the two arms needs it to have
a second arm at all.
"""
monkeypatch.setenv(factory.CHOICE_ENV, "driver")
@@ -4,7 +4,7 @@
four browsers at once, it was 75% of the reader's lag, and it made `networkidle` miss 7 times in 400 (none in 400 once the start no longer
waited). Two listeners of this package started a thread from the reader: `Browser.attachedToTarget` (one thread per adoption) and
`Page.fileChooserOpened` (one thread to announce the chooser). Both now hand the thread to the browser's ONE long-lived starter
(`_ThreadStarter`, made with the browser), which starts it.
(`ThreadStarter`, made with the browser), which starts it.
NO BROWSER HERE: the real dispatchers over a scripted Juggler connection, and every event of the engine delivered FROM A THREAD OF ITS OWN
(the reader's stand-in), the way the connection delivers them. `Thread.start` is replaced by a recorder of the thread that called it.
@@ -127,16 +127,20 @@ def test_an_attached_target_and_a_file_chooser_start_no_thread_on_the_reader(sta
server.shutdown()
def test_the_starter_of_a_browser_ends_with_its_connection(starts):
def test_the_starter_of_a_browser_ends_with_its_connection_and_the_connections_thread_with_the_server(starts):
server, conn, browser, context, opener_target = _world(starts)
try:
starter = browser.thread_starter
starter.start(target=lambda: None, name="invpw-test-started")
assert _wait(lambda: ("invpw-thread-starter", "invpw-test-started") in starts, 3)
conn.announce_closed()
starter._thread.join(5)
assert not starter._thread.is_alive(), "the starter outlived the connection"
starter.start(target=lambda: None, name="invpw-test-after-the-end") # after the end: nothing is started, nothing raises
starter.start(target=lambda: None, name="invpw-test-after-the-end") # after the connection's end: nothing is started, nothing raises
shared = server.thread_starter
assert shared is server.thread_starter, "the server must own ONE starter"
assert shared._thread.is_alive(), "the server's starter must outlive one browser's connection"
server.shutdown()
shared._thread.join(5)
assert not shared._thread.is_alive(), "the starter outlived the server"
assert all(c[1] != "invpw-test-after-the-end" for c in starts)
finally:
server.shutdown()
+4 -2
View File
@@ -258,12 +258,14 @@ class _Page:
def engine(monkeypatch):
monkeypatch.setattr(srv, "PageDispatcher", _Page)
e = _Engine()
browser = BrowserDispatcher(Server(), None, e, "151.0", session_seed=1)
server = Server()
browser = BrowserDispatcher(server, None, e, "151.0", session_seed=1)
e.browser = browser
context = BrowserContextDispatcher(browser.server, browser, {}, "C1")
browser.contexts.append(context)
e.context = context
return e
yield e
server.shutdown() # the connection's one starter ends with its server
def _new_page_in_thread(engine, number, out):
@@ -0,0 +1,268 @@
"""The engine DECLARES software compositing on every machine, and what a page reads does not change by it.
The core declares, in the feature-status table (`zoom.stealth.gfx.feature_status`), the decision that Firefox retail takes on a
virtual machine: the compositing features (WEBRENDER, WEBRENDER_COMPOSITOR, the D3D*_LAYERS, CANVAS2D_ACCELERATION, ...) are
blocklisted with FEATURE_FAILURE_VM_VENDOR, and on Windows the core sets `gfx.webrender.software=true` and
`gfx.webrender.software.d3d11=false`. WebGL, WebGPU and the media features stay as the persona declares them. Three things follow, one test each:
1. the compositor the engine runs is WebRender (Software), on Windows AND on Linux (on Linux this closes the risk that the table,
with no pref beside it, sends the engine down another road);
2. the GPU process, which is where a hardware WebRender spends its CPU, spends almost none on a fixed scene;
3. no byte a page reads of canvas 2D, WebGL, WebGPU, text and the declared values changes: the keys of the probe (the 86 of the first
hunt, WebGPU features and limits read by name, and the canvas 2D scenes added for the canvas blocklist: drawImage scaled up and down
with imageSmoothing off and on at three qualities, text filled and stroked with gradients of three kinds) equal the reference of the
operating system, tests/data/page_bytes_<os>.json.
Known-bad input: the engine with the core of firefox-64 before this declaration (64.71.0). On the Windows runner `gfx.webrender.software`
is false there (the effective prefs of run 43652292533, arm ours) and the GPU process uses 2.7 to 4.2 s on the scene of test 2 (GitHub
Actions runs 43652292533 and 43642744101): tests 1 and 2 are red on it. Whether test 1 is red on Linux with that core is not measured.
How the compositor is read. `Troubleshoot.snapshot().graphics` is what about:support shows and carries `windowLayerManagerType`, but on
this engine the provider throws before it gets there (`ext is null`: it asks WebGL for the chrome-only MOZ_debug extension, which the
engine does not give), so `graphics` is an error string. The test reads what the provider reads, the same two properties of each window
(`windowUtils.layerManagerType` and `.layerManagerRemote`, Troubleshoot.sys.mjs), in chrome scope through Marionette: the route
tests/webfont_probe.py uses (`-marionette -remote-allow-system-access` and MOZ_REMOTE_ALLOW_SYSTEM_ACCESS=1).
"""
from __future__ import annotations
import http.server
import json
import sys
import threading
import time
from pathlib import Path
import pytest
pytestmark = pytest.mark.e2e
OS_NAME = "windows" if sys.platform == "win32" else "linux"
SOFTWARE = "WebRender (Software)"
MARIONETTE_ARGS = ["-marionette", "-remote-allow-system-access"]
#: What a launch is given in the hunt that measured the Windows reference (same seed, locale and timezone, so the same persona).
LAUNCH = dict(seed=42, headless=True, locale="en-US", timezone="Europe/Rome")
# --------------------------------------------------------------------------------------------------------- the privileged reads
WINDOWS_JS = """
const out = [];
for (const win of Services.ww.getWindowEnumerator()) {
try {
const u = win.windowUtils;
out.push([u.layerManagerType, u.layerManagerRemote]);
} catch (e) { out.push(["error: " + e, false]); }
}
return JSON.stringify(out);
"""
PREFS_JS = """
const out = {};
for (const name of arguments[0]) {
const t = Services.prefs.getPrefType(name);
out[name] = t === 32 ? Services.prefs.getStringPref(name)
: t === 64 ? Services.prefs.getIntPref(name)
: t === 128 ? Services.prefs.getBoolPref(name) : null;
}
return JSON.stringify(out);
"""
def _marionette(port):
import webfont_probe
m = webfont_probe._Marionette(port)
m.call("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {}}})
m.call("Marionette:SetContext", {"value": "chrome"})
return m
def _script(marionette, script, args=()):
return json.loads(marionette.call("WebDriver:ExecuteScript", {"script": script, "args": list(args)})["value"])
def _a_page_server(page_html):
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
body = page_html.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
server.daemon_threads = True
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, "http://127.0.0.1:%d/" % server.server_address[1]
# ------------------------------------------------------------------------------------------------ 1. the compositor
def test_the_compositor_is_webrender_software_whatever_the_machine(firefox_binary, monkeypatch):
import webfont_probe
from invisible_playwright import InvisiblePlaywright
monkeypatch.setenv("MOZ_REMOTE_ALLOW_SYSTEM_ACCESS", "1") # the chrome-scope reads below
port = webfont_probe.MARIONETTE_PORT
pref_names = ["zoom.stealth.gfx.feature_status", "gfx.webrender.software", "gfx.webrender.software.d3d11"]
server, url = _a_page_server("<!doctype html><title>compositor</title><body>x</body>")
marionette = None
try:
with InvisiblePlaywright(binary_path=firefox_binary, extra_args=MARIONETTE_ARGS,
extra_prefs={"marionette.port": port}, **LAUNCH) as browser:
page = browser.new_page()
page.goto(url, wait_until="load", timeout=60000)
marionette = _marionette(port)
# a window gets its layer manager a moment after it is shown: the same wait for the answer as about:support has none, so poll
windows, end = [], time.time() + 30
while time.time() < end:
windows = _script(marionette, WINDOWS_JS)
if any(kind not in ("None", "") and remote for kind, remote in windows):
break
time.sleep(0.5)
prefs = _script(marionette, PREFS_JS, [pref_names])
finally:
if marionette is not None:
marionette.close()
server.shutdown()
shown = [kind for kind, remote in windows if kind != "None" and remote]
assert shown, "no window of the engine has a layer manager (windowUtils.layerManagerType, layerManagerRemote): %r" % (windows,)
assert set(shown) == {SOFTWARE}, (
"the compositor of the window(s) is %r on %s, expected %r: the engine did not take the VM decision for the compositing features"
% (shown, OS_NAME, SOFTWARE))
table = {}
for entry in (prefs["zoom.stealth.gfx.feature_status"] or "").split(","):
name, _, rest = entry.partition("|")
table[name] = rest.split("|")
webrender = table.get("WEBRENDER")
assert webrender is not None, "the declared table has no WEBRENDER entry: %r" % (prefs["zoom.stealth.gfx.feature_status"],)
assert webrender[1:2] == ["FEATURE_FAILURE_VM_VENDOR"], (
"WEBRENDER is declared %r, expected blocklisted with FEATURE_FAILURE_VM_VENDOR" % (webrender,))
if OS_NAME == "windows":
assert prefs["gfx.webrender.software"] is True, "gfx.webrender.software is %r on Windows" % (prefs["gfx.webrender.software"],)
assert prefs["gfx.webrender.software.d3d11"] is False, \
"gfx.webrender.software.d3d11 is %r on Windows" % (prefs["gfx.webrender.software.d3d11"],)
# ------------------------------------------------------------------------------------------------ 2. the GPU process
#: The scene of the hunt that measured it (scripts/hunt_cpu_per_browser.py of the branch hunt/cpu-render-path): a page that builds an
#: RTCPeerConnection with no ICE servers and waits for the gather, draws 200 DOM elements and one 2D canvas frame; the browser goes to
#: the next copy of it, 10 times.
ROUNDS = 10
ICE_WAIT_MS = 15000
SCENE = """<!doctype html><meta charset=utf-8><title>scenario</title>
<body><div id=root></div><canvas id=c width=320 height=200></canvas>
<script>
window.__ready = (async () => {
const pc = new RTCPeerConnection({iceServers: []});
pc.createDataChannel("x");
const done = new Promise(res => {
const t = setTimeout(() => res("timeout:" + pc.iceGatheringState), %(ice_wait)d);
pc.addEventListener("icegatheringstatechange", () => {
if (pc.iceGatheringState === "complete") { clearTimeout(t); res("complete"); }
});
});
await pc.setLocalDescription(await pc.createOffer());
const state = pc.iceGatheringState === "complete" ? "complete" : await done;
const root = document.getElementById("root");
for (let i = 0; i < 200; i++) {
const d = document.createElement("div");
d.textContent = "element " + i;
d.style.cssText = "display:inline-block;width:40px;height:16px;margin:1px;background:hsl(" + (i * 7 %% 360) + ",60%%,60%%)";
root.appendChild(d);
}
const g = document.getElementById("c").getContext("2d");
for (let i = 0; i < 40; i++) {
g.fillStyle = "hsl(" + (i * 9) + ",70%%,50%%)";
g.fillRect(i * 8, (i * 5) %% 160, 60, 30);
}
g.font = "16px sans-serif";
g.fillText("a frame of the scenario", 10, 100);
g.getImageData(0, 0, 1, 1);
pc.close();
return state;
})();
</script>
""" % {"ice_wait": ICE_WAIT_MS}
#: CPU seconds the GPU process may use for the 10 scenes of ONE browser, per operating system.
#:
#: WINDOWS: 1.5 s. Measured on the windows-2022 runner (Hyper-V, no real GPU), 4 browsers at once, the same 10 scenes each, GPU process,
#: median per browser: 0.32 s with the VM decision declared (run 43652292533, arm ours_vmretail, mean of two rounds 0.324 s) and 2.7 to
#: 4.2 s without it (run 43652292533, arm ours, 2.68 s, and run 43642744101). Stock Firefox 159 headed on the same runner: 0.004 s.
#: 1.5 s is about 4.7 times what the declared engine used and 0.55 times the least the undeclared one used: a run that is slow for
#: the runner's sake stays under it, and the hardware WebRender, which keeps the GPU process busy for every frame, does not.
#: This test starts ONE browser, which the GPU process has to itself, so it is at most what a browser used when four shared the runner.
#:
#: LINUX: there is no measurement of the GPU process on the Linux runner yet, and there may be no GPU process at all (software
#: WebRender on Linux can run in the parent). The test asserts on what exists: if a GPU process exists its CPU is held to the same bound,
#: and the parent's and the tab's CPU are printed with it. It does not assert that one exists. A first run on Linux says what the numbers
#: are; the bound for it is to be tightened from them, not guessed.
GPU_CPU_LIMIT_S = {"windows": 1.5, "linux": 1.5}
def test_the_gpu_process_is_idle_on_a_fixed_scene(firefox_binary, capsys):
import os
from _cpu_by_type import CpuSampler
from invisible_playwright import InvisiblePlaywright
server, base = _a_page_server(SCENE)
states = []
try:
with InvisiblePlaywright(binary_path=firefox_binary, **LAUNCH) as browser:
page = browser.new_page()
sampler = CpuSampler(os.getpid())
sampler.begin()
try:
for n in range(ROUNDS):
page.goto("%sp/%d" % (base, n), wait_until="load", timeout=60000)
states.append(page.evaluate("window.__ready"))
finally:
cpu = sampler.end()
seen = sorted({kind for kind, _cpu in sampler.last.values()})
finally:
server.shutdown()
with capsys.disabled():
print("\nCPU seconds of the engine by process type over %d scenes of one browser on %s: %s (types seen: %s)"
% (ROUNDS, OS_NAME, json.dumps({k: round(v, 3) for k, v in cpu.items() if v or k in seen}), ", ".join(seen)))
assert states == ["complete"] * ROUNDS, "the scene did not run %d times to its end: %r" % (ROUNDS, states)
assert "parent" in seen and "tab" in seen, \
"no parent and content process of the engine below the test process (seen: %r): the process tree is cut and the CPU is not the browser's" % (seen,)
limit = GPU_CPU_LIMIT_S[OS_NAME]
if OS_NAME == "windows":
assert "gpu" in seen, "the Windows engine has no GPU process (seen: %r); the measurement of the bound had one" % (seen,)
if "gpu" in seen:
assert cpu["gpu"] < limit, (
"the GPU process used %.2f s of CPU for %d scenes of one browser on %s, the bound is %.1f s (all types: %s). With the compositing "
"declared as software it used 0.32 s on the Windows runner (run 43652292533), without it 2.7 to 4.2 s (runs 43652292533, 43642744101)"
% (cpu["gpu"], ROUNDS, OS_NAME, limit, json.dumps({k: round(v, 2) for k, v in cpu.items() if v})))
# ------------------------------------------------------------------------------------------------ 3. what a page reads
def test_the_bytes_a_page_reads_are_the_reference_of_the_system(firefox_binary):
import _page_bytes
from invisible_playwright import InvisiblePlaywright
expression = (Path(__file__).resolve().parent / "page_bytes_probe.js").read_text(encoding="utf-8")
server, url = _a_page_server("<!doctype html><meta charset=utf-8><title>probe</title><body></body>")
try:
with InvisiblePlaywright(binary_path=firefox_binary, **LAUNCH) as browser:
page = browser.new_page()
page.goto(url, wait_until="load", timeout=60000)
measured = page.evaluate(expression)
finally:
server.shutdown()
problems, record = _page_bytes.compare(_page_bytes.load_reference(OS_NAME), measured)
assert not problems, _page_bytes.message(OS_NAME, problems, record)
+30
View File
@@ -0,0 +1,30 @@
"""The leak census runs from conftest in every job, including the ones that install pytest alone. There it must import nothing of the
package: the `version` job of the release pull request failed with `No module named 'invisible_core'` when the census imported
`invisible_playwright._juggler._threads` (which pulls `invisible_playwright._pin`)."""
import subprocess
import sys
import textwrap
from pathlib import Path
TESTS = Path(__file__).resolve().parent
def test_a_census_in_a_process_that_never_loaded_the_package_imports_nothing_and_counts_nothing():
script = textwrap.dedent("""
import sys
sys.path.insert(0, %r)
class _NoPackage:
def find_spec(self, name, path=None, target=None):
if name == "invisible_core" or name.startswith(("invisible_core.", "invisible_playwright")):
raise ImportError("the census imported %%s" %% name)
return None
sys.meta_path.insert(0, _NoPackage())
import _browser_census as census
assert census.starters_alive() == [], census.starters_alive()
assert census.wait_until_back_to(0, seconds=0) == 0
loaded = sorted(m for m in sys.modules if m.startswith(("invisible_core", "invisible_playwright")))
assert not loaded, loaded
print("OK")
""") % str(TESTS)
done = subprocess.run([sys.executable, "-I", "-c", script], capture_output=True, text=True, timeout=60)
assert done.returncode == 0 and done.stdout.strip() == "OK", done.stdout + done.stderr
@@ -0,0 +1,187 @@
"""The helpers of tests/test_software_compositing_is_declared_e2e.py, on known inputs (no browser).
* a PNG is compared by the pixels it decodes to: the same pixels with another per-launch chunk (`deBG`) and another compression are the
same; one pixel changed is not;
* the comparison with the reference names every key that differs, is missing, or is extra, and a missing one carries the entry to record;
* the process type is read from the last argument of `-contentproc`; the CPU of a window is the last value minus the first, a process
born inside it counted whole.
The committed reference of Windows is held to its own shape: every key of the stable part has a value, and every PNG entry has a length.
"""
from __future__ import annotations
import base64
import json
import struct
import zlib
import pytest
import _cpu_by_type as cpu
import _page_bytes as pb
pytestmark = pytest.mark.unit
def _chunk(tag, data):
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
def _png(w, h, rgba, extra=b"", level=6, ftype=0):
rows = b"".join(bytes([ftype]) + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h))
return (pb.PNG_SIGNATURE + _chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0))
+ _chunk(b"IDAT", zlib.compress(rows, level)) + extra + _chunk(b"IEND", b""))
PIXELS = bytes((7 * i + 3) % 256 for i in range(4 * 5 * 4))
def _value(png, data_url=False):
if data_url:
return {"h": "x", "n": len(png) * 2, "b64": base64.b64encode(png).decode()}
return {"h": "x", "n": len(png), "b64": base64.b64encode(png).decode()}
def test_the_same_pixels_with_another_chunk_and_another_compression_are_the_same():
a = pb.decode_png(_png(4, 5, PIXELS, extra=_chunk(b"deBG", b"4620504988720C77"), level=6))
b = pb.decode_png(_png(4, 5, PIXELS, extra=_chunk(b"deBG", b"D5E4439F1FAC5913"), level=1))
assert a == b and a["w"] == 4 and a["h"] == 5 and a["ct"] == 6
def test_one_pixel_changed_is_another_png():
changed = bytearray(PIXELS)
changed[17] ^= 1
assert pb.decode_png(_png(4, 5, PIXELS))["sha256"] != pb.decode_png(_png(4, 5, bytes(changed)))["sha256"]
@pytest.mark.parametrize("ftype", [1, 2, 3, 4])
def test_every_scanline_filter_decodes_to_the_pixels(ftype):
"""The encoder of the engine chooses a filter per row; the decoder must undo each of them. The rows are filtered by hand."""
w, h, bpp = 4, 5, 4
stride = w * bpp
rows = [PIXELS[y * stride:(y + 1) * stride] for y in range(h)]
out = bytearray()
prev = bytes(stride)
for row in rows:
line = bytearray()
for i in range(stride):
left = row[i - bpp] if i >= bpp else 0
up = prev[i]
upleft = prev[i - bpp] if i >= bpp else 0
if ftype == 1:
pred = left
elif ftype == 2:
pred = up
elif ftype == 3:
pred = (left + up) >> 1
else:
pred = pb._paeth(left, up, upleft)
line.append((row[i] - pred) & 255)
out += bytes([ftype]) + line
prev = row
png = (pb.PNG_SIGNATURE + _chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0))
+ _chunk(b"IDAT", zlib.compress(bytes(out))) + _chunk(b"IEND", b""))
assert pb.decode_png(png) == pb.decode_png(_png(w, h, PIXELS))
def test_something_that_is_not_a_png_is_refused():
with pytest.raises(pb.NotAPng):
pb.decode_png(b"GIF89a....")
def _reference_of(measured):
ref = {"keys": {}, "pngs": {}}
for key, value in measured.items():
(ref["pngs"] if pb.is_png_key(key) else ref["keys"])[key] = pb.entry_of(key, value)
return ref
def _measured(png_extra=b"", pixels=PIXELS):
return {
"env.ua": {"s": "Mozilla"},
"c2d.shapes.getImageData": {"h": "abc", "n": 80, "w": 4, "b64": "AAAA"},
"c2d.shapes.png": _value(_png(4, 5, pixels, extra=png_extra), data_url=True),
"c2d.shapes.toBlob": _value(_png(4, 5, pixels, extra=png_extra)),
}
def test_a_launch_equal_to_its_reference_has_no_problem_whatever_its_png_chunk():
reference = _reference_of(_measured(png_extra=_chunk(b"deBG", b"4620504988720C77")))
problems, record = pb.compare(reference, _measured(png_extra=_chunk(b"deBG", b"D5E4439F1FAC5913")))
assert problems == [] and record == {}
def test_a_changed_stable_value_a_changed_pixel_a_missing_and_an_extra_key_are_each_named():
reference = _reference_of(_measured())
changed = bytearray(PIXELS)
changed[0] ^= 9
measured = _measured(pixels=bytes(changed))
measured["env.ua"] = {"s": "Other"}
measured["c2d.scale.off.getImageData"] = {"h": "n", "n": 1}
del measured["c2d.shapes.getImageData"]
problems, record = pb.compare(reference, measured)
text = "\n".join(problems)
assert "env.ua" in text
assert "c2d.shapes.png: the decoded pixels differ" in text and "c2d.shapes.toBlob: the decoded pixels differ" in text
assert "c2d.shapes.getImageData: in the reference and not read by the probe" in text
assert "c2d.scale.off.getImageData: not in the reference" in text
assert list(record) == ["c2d.scale.off.getImageData"]
assert "RECORD-BEGIN" in pb.message("linux", problems, record)
def test_a_reference_that_holds_only_the_length_of_a_png_asks_for_its_pixels():
measured = _measured()
reference = _reference_of(measured)
del reference["pngs"]["c2d.shapes.png"]["sha256"]
problems, record = pb.compare(reference, measured)
assert problems == ["c2d.shapes.png: the reference has the length of this PNG and not yet its decoded pixels"]
assert record["c2d.shapes.png"]["sha256"] == pb.entry_of("c2d.shapes.png", measured["c2d.shapes.png"])["sha256"]
def test_no_reference_file_makes_every_key_a_problem_with_its_entry():
problems, record = pb.compare({"keys": {}, "pngs": {}}, _measured())
assert len(problems) == 4 and sorted(record) == sorted(_measured())
def test_a_png_the_page_read_that_does_not_decode_is_a_problem_not_a_pass():
measured = {"c2d.shapes.png": {"h": "x", "n": 10, "b64": base64.b64encode(b"not a png at all").decode()}}
problems, record = pb.compare({"keys": {}, "pngs": {}}, measured)
assert len(problems) == 1 and "does not decode" in problems[0] and record == {}
def test_a_png_data_url_short_enough_to_be_a_string_is_decoded_too():
png = _png(4, 5, PIXELS)
value = {"s": pb.DATA_PREFIX + base64.b64encode(png).decode()}
entry = pb.png_entry(value)
assert entry["n"] == len(value["s"]) and entry["sha256"] == pb.decode_png(png)["sha256"]
def test_the_keys_that_are_png_files_and_the_ones_that_are_not():
for key in ("c2d.shapes.png", "c2d.shapes.toBlob", "c2d.offscreen.convertToBlob", "gl1.triangle.toDataURL", "c2d.scale.high.png"):
assert pb.is_png_key(key), key
for key in ("c2d.shapes.jpeg", "c2d.shapes.webp", "gl1.triangle.toDataURL_jpeg", "c2d.scale.high.getImageData", "env.ua"):
assert not pb.is_png_key(key), key
def test_the_type_of_a_process_is_the_last_argument_of_contentproc():
assert cpu.classify(["firefox.exe", "-no-remote", "-profile", "p"]) == "parent"
assert cpu.classify(["firefox.exe", "-contentproc", "-parentBuildID", "1", "gpu"]) == "gpu"
assert cpu.classify(["firefox.exe", "-contentproc", "-isForBrowser", '"tab"']) == "tab"
assert cpu.classify(["firefox", "-contentproc", "x", "forkserver"]) == "forkserver"
assert cpu.classify(["firefox.exe", "-contentproc", "weird"]) == "other"
def test_the_cpu_of_a_window_is_the_last_value_minus_the_first_and_a_new_process_counts_whole():
start = {1: ("parent", 10.0), 2: ("gpu", 1.0)}
last = {1: ("parent", 12.5), 2: ("gpu", 1.25), 3: ("gpu", 0.5), 4: ("tab", 2.0)}
out = cpu.delta_by_type(start, last)
assert out["parent"] == 2.5 and out["gpu"] == 0.75 and out["tab"] == 2.0 and out["socket"] == 0.0
def test_the_reference_committed_for_windows_has_the_shape_the_comparison_reads():
ref = json.loads(pb.reference_path("windows").read_text(encoding="utf-8"))
assert ref["os"] == "windows" and ref["source"]
assert ref["keys"] and all(("s" in v) != ("h" in v) for v in ref["keys"].values())
assert all(not pb.is_png_key(k) for k in ref["keys"])
assert ref["pngs"] and all(pb.is_png_key(k) and isinstance(v.get("n"), int) for k, v in ref["pngs"].items())
assert all(len(v["sha256"]) == 64 for v in ref["pngs"].values() if "sha256" in v)
+4 -5
View File
@@ -17,6 +17,7 @@ import math
import pytest
from invisible_playwright._juggler import wire
from invisible_playwright._juggler.dispatcher import Server
from invisible_playwright._juggler.transport import InProcessTransport, JsonWireTransport
pytestmark = pytest.mark.unit
@@ -67,10 +68,11 @@ def test_a_lone_surrogate_survives_the_text():
# ── the transport ──────────────────────────────────────────────────────────
class _Server:
"""What `InProcessTransport` needs of a server: attach, handle, shutdown."""
class _Server(Server):
"""What `InProcessTransport` needs of a server: attach, handle, shutdown, and the one starter it starts its workers through."""
def __init__(self, result):
super().__init__()
self._result = result
self.seen = []
@@ -81,9 +83,6 @@ class _Server:
self.seen.append(message)
return self._result
def shutdown(self):
pass
def _call(transport_class, result, message):
"""Send `message` through a `transport_class` over a server answering `result`;