Files
playwright/tests/test_juggler_injected.py
Federico EliaandClaude Opus 5.5 fcacd9c33d Release 0.51.1 (#486)
* juggler: a popup's page is handed from its buffer to its dispatcher in one step, so no commit or load between the snapshot and the hook is lost (DRAFT)

What the client is told of a frame comes from the initializer (a snapshot of what the lifecycle knew when the frame dispatcher was made)
and from the lifecycle's announcements through a hook that the page installs at the end of its construction. An event the lifecycle heard
after the snapshot and before the hook was told to nobody: the commit of a popup's destination left the client's frame at about:blank for
good, and the DOMContentLoaded/load held in the same period were dropped with every held event that is not a Network.* one. Measured on
Windows with the in-process client and no route on the context: the popup "is at about:blank", or wait_for_load_state("load") times out.

_hear_lifecycle installs the hook and reconciles the frames in one step with the lifecycle's lock held: frames born or gone, the document a
frame committed, its load states; each difference is said once (a frame dispatcher now remembers the load states the client was told). A
commit also drops the load states said before the announcement for the document it replaces, so the replay after the `page` event is the
destination's and not the blank page's.

Tests: test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once (the destination's commit, DOMContentLoaded and load at every
placement among four points of the passage: 16 of 20 orders red on the code as it was; and the commit before or during the announcement:
2 of 2 red), green on this change. The fixtures of two white-box tests get the attributes the page now keeps.

* juggler: the hand-over of a popup's page gives back EVERY event held while it was built, in the order it arrived (DRAFT, 0.51.1)

The page's own listener holds the events of the period between its construction and the end of _install_events, and the hand-over gave
back only the Network.* ones: a console message, a pageError, a dialog, a crash or any other event that came in that period was dropped.
A dialog is the worst: alert() blocks the page until the client accepts it, and a client never told of it cannot. Every held event is now
delivered, whatever its kind, in the order it arrived and once (the events the lifecycle owns are also reconciled, which is idempotent).

Tests: one event of each family (console, pageError, dialog, crash) in this order at every placement among four points of the passage,
35 orders, 34 red on the hand-over as it was; each is told once and in order, the dialog is known to the page and the console message is in
its log; and accepting a dialog opened during the passage sends the engine the answer that unblocks the page (3 points).

* juggler: an event beyond the cap of the hold is counted and said once; a file chooser opened during the hand-over reaches the client; CHANGELOG (DRAFT, 0.51.1)

The hold of a page being built keeps at most HELD_CAP events (it bounds the memory of a page that never finishes building). The events beyond
it are counted and, when the hold ends, said once with their count in a RuntimeWarning, instead of vanishing.

Tests: the cap (a loss said once, with its count), and a file chooser opened at each of four points of the hand-over reaches the client with
the handle of its input element and its isMultiple (the scripted engine answers the three commands the chooser needs). The fixture of
test_a_closed_page_says_nothing gets the counter the page now keeps. CHANGELOG: Fixed, for 0.51.1.

* ci: every leg launches with a GeoIP database made by the repository (same bytes every run, no download, no licensed data); the release alone looks at the real one

scripts/ci_lab_geoip.py writes a MaxMind DB with the six networks of the realness exits and the fields the core reads (an ip_version 6 tree, the types libmaxminddb checks),
refuses to go on when its bytes are not the sha256 of ci/geoip.json, exports STEALTHFOX_GEOIP_MMDB to the job, and says in 'evidence' which file a launch ran with;
scripts/ci_verdict.py judge --geoip --geoip-pin turns a leg that ran without it, or with another, red. tests.yml, e2e.yml and webrtc-e2e.yml make it before pytest;
user-install.yml is left alone. publish.yml (the release) runs scripts/ci_real_geoip_check.py before the upload: the product's own download road, the lab database against the real
one for the six exits, every time_zone of the real database known to the runner.

* tests: the two white-box fixtures that build a PageDispatcher by hand get the attributes the hand-over now keeps

test_navigation_response.py and test_same_document_navigation.py build a PageDispatcher with object.__new__ and set by hand the
attributes the code under test touches; the hook of the lifecycle (_on_lifecycle commit, _hear_lifecycle) now reads _announce_lock,
_announced, _said_before_announcement, _frames and _told_attached, and the frame stubs need frame_id and told_states. They are not marked
unit, so the first full run (-m unit) did not reach them; the run without the e2e marker does. No assertion is touched.

* tests: ONE picker for 'the same number on TCP and UDP', used by the HTTP/3 server, the witness and the resolver trap (for 0.51.1)

tests/_ports.py has the sequence of numbers (the system's own pick, then numbers drawn below the ephemeral range, 200 tries) and the picker that keeps every refusal with its code. The HTTP/3 server
calls it (repos-2e's own copy of the loop is gone), the witness walks the same sequence instead of its own, and so does the resolver trap when its port is 0; a port asked for (53 on the root leg)
is tried once per address as before. The test that holds a port for the trap picks it with the picker too: its own system pick fell in a refused UDP block on a work machine (WinError 10013).
Unit tests with a fake socket layer that refuses a contiguous block of 200 UDP ports, for the server, the witness and the trap.

* tests: the hand-over of a popup under concurrency, five sequences (RED on 7d934a6: a load told twice, an event that overtakes the held ones, a frame created after the page's dispose, a frame made twice, a same-address commit not told)

Test only. A-D go green with the changes listed in the review (E not tried).

* juggler: the hand-over of a popup holds under concurrency (a load told once, the held events keep their order, a document at the same address is told, a closed page is not given frames or announced, one dispatcher per frame) (DRAFT, 0.51.1)

From the concurrency review of 7d934a6 (five sequences, tests/test_the_hand_over_of_a_popup_holds_under_concurrency.py):
- FrameDispatcher.emit tells a load state once; the replay after the announcement keeps one entry per (frame, state) even when the
  client knows it from the snapshot, and says it again on purpose.
- the hold ends only when a round finds it empty; the rounds are delivered outside the lock, so a live event never overtakes a held one.
- the reconciliation compares the place of the last commit, not only (url, name).
- _hear_lifecycle and _reconcile_frames do nothing on a closed page; announce() does not say `page` for a page closed before it.
- frame_for checks and creates under a recursive lock.
The five files of the hand-over are in wrapper.unit.page (62).

* juggler: the hold gives back in at most four rounds outside the lock, then the rest with the lock held (a page that prints in a tight loop cannot keep it open) (DRAFT, 0.51.1)

* juggler: a live event of the engine never overtakes the replay of the events a new page missed (the cause of the popups left at about:blank on engine 63) (DRAFT, 0.51.1)

The browser buffers the events of a session nobody reads yet and `PageDispatcher` is handed them (`replay`) after it subscribed its
lifecycle and injected script. The replay ran on the adoption thread while the engine's reader went on delivering live events to the same
subscribers: the destination's commit (live) fell into the middle of the replay of the popup's first events and the replay then brought
older ones after it - the initial about:blank (no id) and the navigationStarted of the same navigation. The lifecycle ended at about:blank
(a popup at about:blank), or had its navigation pending again (Execution context was destroyed). The second Page.frameAttached of every popup
in the traces of the proof is the replay: the engine sends each event once.

The reader takes a gate for each event of a session; the page takes it for "subscribe, then replay" as one step (BrowserDispatcher.events_gate),
with a bounded wait for the reader (5 s) so a holder that never lets go cannot stop the engine's stream.

Test: tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py, five stops of the replay, RED on the old code (the lifecycle
ends at about:blank), green with the gate. wrapper.unit.page 62 -> 67.

* juggler: the gate of the events belongs to the connection, looks the delivery up at each event, and bounds the hold, not each event (DRAFT, 0.51.1)

From the review of 80bc478:
- the wrapper froze the bound `dispatch_event` of the connection: a patch of the class made after the browser was built (the e2e fixtures that
  record the events) was bypassed. It looks the delivery up at each event, as the reader did.
- the 5 s bound was per event: a holder that never lets go made the reader pay 5 s for every event. After one timeout the reader delivers ungated
  for 30 s, and the connection records it (`handler_errors`).
- the gate is kept on the connection, so a second dispatcher over the same connection shares the one the wrapper takes.
Tests: a utility context created while the replay goes on is not undone by an older event (the injected script half), the class patch, the
hold bound; wrapper.unit.page 67 -> 71.

* juggler: a page that is being built waits at most 30 s for the gate of the events, and says it when it does not get it (DRAFT, 0.51.1)

From the reading of 15d1891 by repos-6b: the construction of a page waited for the gate with no bound, a new dependency on the reader. It now
builds without the gate after 30 s and warns. wrapper.unit.page 71 -> 72.

* tests: the 17 CodeQL alerts of PR 483 are fixed in the test code (TLS floor, exact host, own address, header from the dict's key, MD5 declared not for security)

py/insecure-protocol x11 (23-33): every client TLS context the fake servers' tests make sets minimum_version = TLS 1.2 (test_the_fake_doh_answers x7,
test_the_fake_doh_delays_and_refuses, test_the_h3_line_helpers, test_the_http_proxy_helper_asks_for_credentials, test_the_udp_chain_helper).
py/bind-socket-all-network-interfaces (37): the TURN stand-in listens on the address the browser is told to connect to, not on 0.0.0.0.
py/http-response-splitting (39): the Content-Disposition name is the dict's own key, found by comparison, nothing of the request is written back.
py/incomplete-url-substring-sanitization (38): the trap's description is compared whole, not searched for a host name.
py/weak-sensitive-data-hashing x3 (34, 35, 36): the TURN long-term credential key IS MD5(user:realm:password) (RFC 5389 15.4); the stand-in and its test
compute it with usedforsecurity=False. Whether CodeQL accepts that is seen on the next scan; no setting touched, no alert closed.

* tests: Control+A selects all in an input and a textarea, in-process and served to the stock client (e2e, red on the keyboard that held Shift for the capital A)

* ci: e2e.yml runs the Control+A e2e on Windows, on the published engine, as a job of its own (dispatchable alone with only=windows-control-a)

tests/test_control_a_selects_all_in_a_field_e2e.py (5 ways to press the shortcut x an <input> and a <textarea>, in-process and served to the stock
client) is red on the keyboard that held Shift for the capital A and was measured on Linux; the keyboard of a user is Windows. The new job
installs the wrapper (which pins the core of the release), fetches the published engine and runs that file on windows-latest with bash as the
shell, behind the same core-on-index gate as the Linux job: skipped with the reason in the summary until the core is on the index. The
workflow_dispatch input `only` lets it run alone (`windows-control-a`) without the 40 minutes of the Linux job.

* ci(install): the wait for the index asks both installers of the job (pip and uv), three rounds in a row, and a call that does not answer is a no

The job installs with two tools: the upgrade test with pip, the release test with uv (the README's way in). The wait asked only pip, so a green wait said nothing
about the page uv would be served, and one yes proves one request, not the next. Each round now asks `pip download` AND `uv pip compile` of
`invisible-playwright==X` (no cache, nothing installed); the job goes on after three rounds in a row in which both said yes (INDEX_WAIT_CONFIRMATIONS), 15 s apart,
a no starts the count again, a call that does not answer in 120 s (INDEX_WAIT_CALL_SECONDS) is a no; the bound of ten minutes is the same and the error says
which installer said no. The harness environment gets `uv` (a PyPI package: `python -m uv`), independent of the uv the release test installs in its own home.

Test: the script of the step runs with a pip and a uv that answer as plans say; red on the step of 299fc9f (8 of 10). The same remedy as invisible_core 2089b48.

* tests: the GeoIP check of e2e.yml anchors on the step's name on main ("..., without the root ones")

The rebase of the 0.51.1 stack over main (c70a396d, 3be9c0b) met the e2e step renamed by 0.51.0's root step; the database is
still made before it and verified after the root step.

* tests: the raw juggler e2e wait for Page.ready and the main frame, not a fixed 0.4-0.5 s

The Windows census of all the e2e (run 43307193708) and the recheck on 87a4e3b (run 43313222398) had 6-7 of these tests red
with "no frame: the page has not announced its main frame yet": on a Windows runner the page is announced after the sleep.
The page is the caller's when the engine says Page.ready, as Playwright hands it over (Lifecycle.wait_for_page_ready), and
then its main frame is there (wait_for_main_frame).

* ci: the sandbox e2e runs in a step that turns user namespaces on; the consecutive-port tests run serially; CHANGELOG for 0.51.1

The sandbox e2e (tests/test_the_socket_process_is_sandboxed_e2e.py) fails on a runner whose AppArmor refuses
user namespaces to a normal user. e2e.yml now leaves it out of the normal run by name (SANDBOX_FILES) and runs
it, after the run and the root step, in a step of its own that sets
kernel.apparmor_restrict_unprivileged_userns=0 first and refuses anything but exactly one passed test.

The two tests of test_declared_host_network_e2e.py that read a consecutive pair of host ports (N, N+1) carry
the wall_clock marker: the e2e run gives them the machine alone, so no other worker can take port N+1.

Each has a unit test that is red on the previous tree. CHANGELOG: the measured popup and Control+A results,
the test fixes, and the known issue this release fixes is removed.

* tests: no address is written out in the GeoIP lab table and its tests (built from numbers, as tests/_realness_support.py does); ci/geoip.json drops its unused network list

* tests: a DoH handshake the client dropped is not a refused certificate (Windows: ConnectionAbortedError 10053)

Windows census of 12/11 (run 43333574229): test_resolver_race_e2e[context_without_proxy_beside_a_proxied_one] read a
ConnectionAbortedError [WinError 10053], through the gateway of a context that HAS the certificate exception, as "a context
without the FakeDoh certificate exception used the DoH". A connection the browser drops before the handshake ends says
nothing about the certificate; only a TLS alert from the client (unknown CA, bad certificate) does. FakeDoh.certificate_refusals()
keeps those; the four e2e that judged every failed handshake (resolver race x2, context-only proxy, DoH under stress) judge the
refusals and still print every failure. Unit test red on the old FakeDoh (no certificate_refusals), green now.

* tests: the GeoIP lab database answers every public address that is not reserved with one declared record

A launch with no proxy asks the database for the runner's egress address, which is not known in advance (any provider, any region). With the six
exits alone the lab database ended those launches in 'egress IP not present in the geoip database' (run 43351424907: 495 errors of this one cause in
the e2e job, and 3 tests of the unit legs). The reserved ranges stay absent, as in the real database. Test red on the six-network database.

* tests: the two gather tests that compare a near and a far duration run alone, in the serial group

Run 43353896238 (Linux e2e, four workers): 765 passed, one failed with (350 - 84) <= 100, the host candidate of the far gather 266 ms after the
near one. The verdict is a difference of two wall-clock measures, which the e2e run gives the machine alone (wall_clock). A unit test reads the file and
refuses any test that compares a near and a far timing without the marker; it is red on the file as it was.

* tests: every suite of the gate and the e2e and unit tests of a pull request run on Linux and Windows, or say why not

Federico, 12/11: a test seen only on Linux proves nothing about the system the product imitates; where Windows behaves
differently the test adapts. A row of ci/required-suites.json names both systems, or a windows_twin, or a linux_only reason;
the jobs of e2e.yml that run scripts/run_e2e.py cover both runners between them; the unit job of tests.yml runs on both.
wrapper.e2e.udp.exit and wrapper.e2e.udp.sandbox are declared linux_only with their reason (the lab's exit address cannot
be held on the runner's adapter without taking the runner off the network; the sandbox twin needs a retail measurement).
Known-bad: the files of 12/11 (two Linux-only rows without a reason, e2e on ubuntu only) -> problems names each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: e2e.yml runs the e2e on Windows too, in four parts, without the linux_only suites

Before this, 562 of the 808 e2e had never run on Windows in any round (census of 12/11, run 43307193708, ~50 minutes in one
job). Four jobs "e2e (windows, part N)" on windows-2022, the published engine, scripts/run_e2e.py as on Linux; the sorted e2e
files split every fourth; the suites ci/required-suites.json declares linux_only are left out by reading the file, not by a
skip. scripts/e2e_is_green.py already reads every e2e check-run of the commit, so the release waits for the Windows parts too.
The root-step test finds the Linux run by its xvfb-run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: the unit tests run on Windows at both ends of the Python range (3.11 and 3.14), not on 3.12 alone

Federico, 12/11: every test on Linux AND Windows. Ubuntu keeps the whole range.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: webrtc-e2e.yml goes (dispatch only, Linux only); its file runs in e2e.yml on Linux and Windows and in the gate

Its one test file, tests/test_webrtc_realness.py, is e2e: e2e.yml collects it on every pull request on both systems, and the
gate's wrapper.e2e.udp lists its UDP-line tests. A workflow that only a person can start is not a round; it is deleted, not
left off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: the Windows parts of e2e.yml launch with the repository's GeoIP database and verify it, as the Linux run does

tests/test_ci_workflows_build_the_geoip_database.py judges each leg of e2e.yml on its own (the Linux job, the Windows parts)
and no longer names webrtc-e2e.yml, which is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: the raw juggler e2e subscribe the page's Lifecycle and injected script on the attach, not after it

Windows CI of 13/11 (run 43373058301, e2e windows part 2): test_juggler_actions [engine-approach] waited 30 s and "the
engine never said Page.ready (frames seen: [])". The connection hands each event to the listeners of that moment
(EventListeners.dispatch_event copies the list); these tests built the Lifecycle from the test thread after polling for the
attach, so the page's first frameAttached and Page.ready, delivered in between, reached no one. Built in the attach
listener, on the reader thread, they are subscribed before the next event of the session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: the fake HTTP/3 server closes its event loop on its own thread (a loop left to the garbage collector hung Windows runs)

PR #486, e2e windows part 1, twice; the Windows hunt of 13/11 (run 43377799126) three runs of fifteen: a test of
test_http3_through_the_proxy_e2e.py stood for minutes and was killed by the timeout. The server had answered every call;
the test thread was in base_events.__del__ -> proactor_events.close -> windows_events.close -> _poll in all three dumps.
H3Server.close() stopped its loop and never closed it, so BaseEventLoop.__del__ closed it later on whatever thread the
garbage collector ran in, and the Windows proactor waited for ever for the UDP receive still pending on it. The loop is now
closed on its own thread after the QUIC server, and close() joins the thread. Unit test red on the old server, green now;
wrapper.unit.udp counts 222.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: the late element is scheduled by the test, and the cross-origin button is waited for before it is counted

Windows CI of 13/11 (PR #486, run 43383366904), two reds of the tests themselves:
- test_juggler_transport::test_the_public_API_WAITS_for_an_element_that_arrives_late: the page's timer (800 ms from its
  load) had already added the element when the test first read it ("the element was already there"); the test now empties
  it and schedules it itself, 800 ms from its own read.
- test_cross_origin_iframe::test_cross_origin_iframe_frame_locator_resolves_button: Locator.count() does not wait, and the
  cross-origin document of the iframe, in its own process, loaded after the count (0 elements); the button is waited for first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pin invisible-core 63.68.0 (the font-manifest cache on Windows, host environment, GeoIP once a day)

* tests: core 63.68.0 no longer declares gfx.webrender.all (a pref that does nothing)

* tests: a move with a button held carries buttons=1 and pressure 0.5 (core 63.68.0); the timed typing test runs in the serial group

* tests: the first-STUN-datagram timing runs in the serial group (419 ms under four parallel browsers on Windows)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 13:26:47 +01:00

362 lines
14 KiB
Python

"""The injected script called from Python: selectors, actionability, and
the check that matters - that our client does not cross into the page
realm.
"""
from __future__ import annotations
import http.server
import importlib.util
import pathlib
import tempfile
import threading
import time
import pytest
from invisible_core.juggler import injected as ini
from _servers import LocalServer
PAGE = b"""<!doctype html><html><head><title>actionable</title></head><body>
<h1 id=title>hello world</h1>
<button id=ok>press</button>
<button id=off disabled>off</button>
<div id=invisible style="display:none">you can't see me</div>
<input id=field placeholder=type>
<div data-testid=tagged>with testid</div>
<p class=three>a</p><p class=three>b</p><p class=three>c</p>
</body></html>"""
def _serve(body):
class H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *a):
pass
return H
def _open(binary, body):
"""Launches, navigates, and returns (connection, lifecycle, injected,
frame, close)."""
from invisible_core.launch import build_launch_plan
from invisible_core.juggler import connection as conn
from invisible_core.juggler.lifecycle import Lifecycle
profile_dir = tempfile.mkdtemp(prefix="inj_test_")
plan = build_launch_plan(5, profile_dir=profile_dir, binary_path=binary, timezone="UTC",
locale="en-US")
srv = LocalServer(("127.0.0.1", 0), _serve(body))
threading.Thread(target=srv.serve_forever, daemon=True).start()
c = conn.launch(binary, profile_dir, headless=True, env=plan.env)
# ⛔ THE PAGE'S LISTENERS ARE BORN ON THE ATTACH, on the reader thread, before the next event of the session is delivered:
# the connection hands each event to the listeners of that moment (dispatch_event copies the list), so a Lifecycle built
# later from this thread missed the page's first frameAttached and Page.ready when they came in between, and waited for
# ever (Windows CI of 13/11, run 43373058301 part 2: "the engine never said Page.ready (frames seen: [])").
sessions: dict = {}
c.add_listener(lambda m, p, s: (
sessions.__setitem__(p["targetInfo"]["targetId"], (p["sessionId"], Lifecycle(c, p["sessionId"]),
ini.InjectedScript(c, p["sessionId"])))
if m == "Browser.attachedToTarget" else None))
c.send("Browser.enable", {"attachToDefaultContext": True})
ctx = c.send("Browser.createBrowserContext", {"removeOnDetach": True})
page = c.send("Browser.newPage",
{"browserContextId": ctx["browserContextId"]})
deadline = time.time() + 20
while page["targetId"] not in sessions and time.time() < deadline:
time.sleep(0.02)
sess, lifecycle, inj = sessions[page["targetId"]]
inj.install()
# Page.ready, not a fixed 0.4 s: the Windows census lost that race (run 43307193708).
lifecycle.wait_for_page_ready(30)
lifecycle.wait_for_main_frame(30)
lifecycle.goto("http://127.0.0.1:%d/" % srv.server_address[1],
until="load", timeout=30)
def close():
c.close()
srv.shutdown()
return c, lifecycle, inj, lifecycle.main_frame, close
# ── without a browser ───────────────────────────────────────────────────────
def test_the_world_name_is_OUR_forks():
"""⛔ Upstream calls it something else: our fork renamed it because it
traveled on the page's window. If this constant and the driver
diverge, the hookup breaks SILENTLY - the context is born, but under
a different name, and nobody recognizes it."""
assert ini.UTILITY_WORLD == "__ctx_aux__"
def test_the_injected_script_is_OURS_not_upstreams():
"""A blob extracted from an upstream bundle would lose every stealth
fix without anything raising an error."""
js = pathlib.Path(ini.__file__).with_name("injected.js").read_text(
encoding="utf-8", errors="replace")
assert "MODIFIED by invisible_playwright" in js
assert "InjectedScript" in js
for engine in ("internal:role", "internal:testid", "internal:label"):
assert engine in js, engine
def test_the_options_declare_the_utility_world_and_NOT_underTest():
"""Both options are still required, but for the reasons that survived
measurement.
⛔ THIS DOCSTRING USED TO CLAIM THAT `isUtilityWorld` TRUE KEPT 13
LISTENERS OFF THE PAGE. It did not. `this.window` in the utility world is
the page's window seen through an Xray, so the constructor's calls landed
on the page in either world; the flag only decided whether they happened
once or once per InjectedScript. The listeners are gone now, installed by
the action that needs them and removed when it stops, and
`tests/test_injected_page_surface.py` measures that rather than asserting
it here.
What each option is still worth: `isUnderTest` false, or the constructor
plants an ENUMERABLE `window.__injectedScript` on the page; and
`isUtilityWorld` true, which is simply the truth about where this runs
and which the bundle reads for its own behaviour.
"""
source = pathlib.Path(ini.__file__).read_text(encoding="utf-8")
assert '"isUtilityWorld": True' in source
assert '"isUnderTest": False' in source
# ── with a browser ──────────────────────────────────────────────────────────
@pytest.mark.e2e
def test_the_selector_engines_respond(firefox_binary):
c, lifecycle, inj, f, close = _open(firefox_binary, PAGE)
try:
for sel in ("#title", "css=#ok", "text=hello world",
"internal:testid=[data-testid='tagged']",
"xpath=//button[@id='ok']"):
oid = inj.query_selector(f, sel)
assert oid, "selector %r found nothing" % sel
inj.dispose(f, oid)
assert inj.query_selector(f, "#doesnotexist") is None
assert inj.count(f, ".three") == 3
finally:
close()
@pytest.mark.e2e
def test_actionability_DISTINGUISHES_instead_of_always_saying_yes(
firefox_binary):
"""⛔ THE KNOWN-BAD INPUT OF THIS FILE.
`checkElementStates` is ASYNCHRONOUS. If the function calling it did
not await it, it would return a Promise, the Promise is a truthy
object, and EVERY element would come out actionable - including a
disabled button and a div with `display:none`. An actionability
check that always says yes is not a check, and the failure would be
silent.
Here we demand that it DISCRIMINATES, and that it says WHICH state
is missing.
"""
c, lifecycle, inj, f, close = _open(firefox_binary, PAGE)
try:
full_states = ["visible", "stable", "enabled"]
ok = inj.element_states(f, inj.query_selector(f, "#ok"), full_states)
assert ok == {"ok": True}, ok
off = inj.element_states(f, inj.query_selector(f, "#off"), full_states)
assert off["ok"] is False and off["missing"] == "enabled", off
invisible = inj.element_states(
f, inj.query_selector(f, "#invisible"), ["visible"])
assert invisible["ok"] is False and \
invisible["missing"] == "visible", invisible
field = inj.element_states(
f, inj.query_selector(f, "#field"),
["visible", "stable", "enabled", "editable"])
assert field == {"ok": True}, field
finally:
close()
@pytest.mark.e2e
def test_the_text_reads(firefox_binary):
c, lifecycle, inj, f, close = _open(firefox_binary, PAGE)
try:
oid = inj.query_selector(f, "#title")
assert inj.text_content(f, oid) == "hello world"
finally:
close()
@pytest.mark.e2e
def test_a_javascript_that_THROWS_arrives_as_an_error_not_as_None(
firefox_binary):
"""⛔ A page exception does NOT come back as a protocol error: it
comes back as `exceptionDetails` inside a SUCCESSFUL response.
Whoever looks only at the return code reads `None` and proceeds with
a value that does not exist."""
c, lifecycle, inj, f, close = _open(firefox_binary, PAGE)
try:
with pytest.raises(ini.EvaluationError) as e:
inj.evaluate(
f, "(() => { throw new Error('broken on purpose'); })()")
assert "broken on purpose" in str(e.value)
finally:
close()
READING = b"""<!doctype html><html><head><title>reading</title></head><body>
<div id=t>hello <b>world</b></div>
<input id=field value=foo>
<input id=ticked type=checkbox checked>
<button id=off disabled>no</button>
<div id=hidden style=display:none>x</div>
<a id=link href="/here">go</a>
</body></html>"""
@pytest.mark.e2e
def test_the_DOM_READING_group(firefox_binary):
"""The operations from item 6, group "DOM reading" (§6.5)."""
c, lifecycle, inj, f, close = _open(firefox_binary, READING)
try:
assert inj.title(f) == "reading"
assert inj.content(f).startswith("<!DOCTYPE html>")
t = inj.query_selector(f, "#t")
assert inj.inner_text(f, t) == "hello world"
assert inj.inner_html(f, t) == "hello <b>world</b>"
box = inj.bounding_box(f, t)
assert box and box["width"] > 0 and box["height"] > 0, box
assert inj.input_value(f, inj.query_selector(f, "#field")) == "foo"
link = inj.query_selector(f, "#link")
assert inj.get_attribute(f, link, "href") == "/here"
# ⛔ A MISSING attribute returns None, not the empty string: they
# are two different things and whoever reads it must be able to
# tell them apart.
assert inj.get_attribute(f, link, "doesnotexist") is None
# a hidden element has no quad: None, not a zero-sized box
assert inj.bounding_box(f, inj.query_selector(f, "#hidden")) is None
finally:
close()
@pytest.mark.e2e
def test_states_DISCRIMINATE_instead_of_always_saying_true(firefox_binary):
"""⛔ THE SECOND KNOWN-BAD INPUT OF THIS FILE.
`injected.elementState` does NOT return a boolean: it returns
`{matches, received}`. Reading it as a boolean would give `True`
always, because a non-empty dict is truthy - and every element
would come out visible, enabled and checked. A check that always
says yes is not a check.
"""
c, lifecycle, inj, f, close = _open(firefox_binary, READING)
try:
assert inj.element_state(
f, inj.query_selector(f, "#t"), "visible") is True
assert inj.element_state(
f, inj.query_selector(f, "#hidden"), "visible") is False
assert inj.element_state(
f, inj.query_selector(f, "#hidden"), "hidden") is True
assert inj.element_state(
f, inj.query_selector(f, "#off"), "disabled") is True
assert inj.element_state(
f, inj.query_selector(f, "#off"), "enabled") is False
assert inj.element_state(
f, inj.query_selector(f, "#ticked"), "checked") is True
assert inj.element_state(
f, inj.query_selector(f, "#field"), "editable") is True
finally:
close()
@pytest.mark.e2e
def test_reads_that_make_no_sense_are_REJECTED(firefox_binary):
"""An `input_value` on a div and a made-up state would come back as
`undefined` silently. A value that means nothing is worse than an
error, because it lets execution continue."""
c, lifecycle, inj, f, close = _open(firefox_binary, READING)
try:
with pytest.raises(ini.EvaluationError) as e:
inj.input_value(f, inj.query_selector(f, "#t"))
assert "input" in str(e.value)
with pytest.raises(ValueError) as e2:
inj.element_state(
f, inj.query_selector(f, "#t"), "wheneverIFeelLikeIt")
assert "unknown" in str(e2.value)
finally:
close()
@pytest.mark.e2e
def test_OUR_CLIENT_DOES_NOT_CROSS_into_the_page_realm(firefox_binary):
"""The check that matters more than any other.
Reuses the trap page from the crossings gate - twenty traps armed in
the FIRST script - but drives it with `_juggler` instead of
Playwright. If the driver was clean and our client was not, the
defect is ours, and this test is the only place that would say so.
"""
spec = importlib.util.spec_from_file_location(
"oc", str(pathlib.Path(__file__).resolve().parents[3]
/ "tests" / "gates" / "observable_crossings.py"))
if spec is None or not pathlib.Path(spec.origin).is_file():
pytest.skip("the trap page lives in the workbench, not here")
oc = importlib.util.module_from_spec(spec)
spec.loader.exec_module(oc)
c, lifecycle, inj, f, close = _open(firefox_binary, oc.PAGINA)
try:
alive = inj.call(f, "(injected) => document.getElementById('spia')"
".getAttribute('data-viva')")
assert alive == "1", (
"traps NOT hooked (%s): a zero would be worth nothing" % alive)
def read():
time.sleep(0.15)
g = inj.call(f, "(injected) => document.getElementById('spia')"
".getAttribute('data-conta') || ''") or ""
counts = {}
for x in g.split():
k, _, v = x.partition("=")
try:
counts[k] = int(v)
except ValueError:
pass
return counts
before = read()
assert before, "the page did not publish the counters"
for action in (lambda: inj.query_selector(f, "#bersaglio"),
lambda: inj.count(f, "div"),
lambda: inj.query_selector(f, "text=cliccami"),
lambda: inj.element_states(
f, inj.query_selector(f, "#bersaglio"),
["visible", "stable", "enabled"]),
lambda: inj.text_content(
f, inj.query_selector(f, "#bersaglio")),
lambda: inj.evaluate(f, "({a: 1, b: [1,2,3]})")):
action()
after = read()
moved = {k: after[k] - before.get(k, 0)
for k in after if after[k] - before.get(k, 0)}
assert not moved, "our client crossed over: %s" % moved
finally:
close()