Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5a1679283 | ||
|
|
1202de8a7b | ||
|
|
eab5bf16b9 | ||
|
|
69edd4db74 |
No files matched your search
@@ -6,6 +6,27 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.39.0] - 2026-10-18
|
||||
|
||||
### Fixed
|
||||
- **`expect()` works for every condition, not two families.** The server
|
||||
re-wrote Playwright's assertions in Python one condition at a time and had
|
||||
written `to_have_count` and the `to_be_*` states; `to_have_text`,
|
||||
`to_contain_text`, `to_have_value`, `to_have_values`, `to_have_attribute`,
|
||||
`to_have_class`, `to_contain_class`, `to_have_css`, `to_have_id`,
|
||||
`to_have_js_property`, `to_be_focused`, `to_be_empty`, `to_be_in_viewport`,
|
||||
`to_have_title`, `to_have_url` and the accessibility ones answered "is not
|
||||
implemented yet". Each reading is now Playwright's own `expect`, from the
|
||||
injected script this package already ships, called the way Playwright's
|
||||
server calls it: strict mode, `element(s) not found`, and a JavaScript error
|
||||
that ends the wait with its message. On Playwright's own suite, its expect
|
||||
tests on firefox-49 went from 30 of 94 passing to 75, with none lost.
|
||||
- `to_have_js_property` with an object, an array or a date as the expected
|
||||
value is refused by name: the page's value lives in another realm, and
|
||||
comparing it would always report a difference. Primitives are compared.
|
||||
`to_match_aria_snapshot` is refused by name too: its template is YAML that
|
||||
Playwright's server parses, and this one has no parser for it.
|
||||
|
||||
## [0.38.0] - 2026-10-18
|
||||
|
||||
The pin moves to invisible-core 49.46.0. The desktop settings a page can read -
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "invisible_playwright"
|
||||
version = "0.38.0"
|
||||
version = "0.39.0"
|
||||
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
|
||||
@@ -194,7 +194,12 @@ def main() -> int:
|
||||
import os
|
||||
env = dict(os.environ)
|
||||
env["INVPW_BINARY_PATH"] = a.binary
|
||||
env["PYTHONPATH"] = str(ROOT)
|
||||
# ⛔ THIS CHECKOUT'S `src` TOO, or the suite measures whatever wrapper is
|
||||
# INSTALLED: `ROOT` alone only makes `scripts._upstream_alias` importable,
|
||||
# and `invisible_playwright` then resolves to the editable install, which
|
||||
# from a worktree is somebody else's tree on somebody else's commit. A
|
||||
# branch measured that way reports main's numbers as its own.
|
||||
env["PYTHONPATH"] = os.pathsep.join([str(ROOT), str(ROOT / "src")])
|
||||
|
||||
if not a.per_file:
|
||||
print("running: %s" % " ".join(argv[3:]))
|
||||
|
||||
@@ -42,7 +42,8 @@ from invisible_core.juggler.actions import Actions
|
||||
from invisible_core.juggler.deadline import Deadline
|
||||
from .dispatcher import (Dispatcher, ExpectNotMet, ProtocolException,
|
||||
Server)
|
||||
from invisible_core.juggler.injected import ContextDestroyed, InjectedScript
|
||||
from invisible_core.juggler.injected import (ContextDestroyed, EvaluationError,
|
||||
InjectedScript)
|
||||
from invisible_core.juggler.keyboard import MODIFIER_MASK
|
||||
from invisible_core.juggler.lifecycle import Lifecycle
|
||||
|
||||
@@ -1400,70 +1401,147 @@ class FrameDispatcher(Dispatcher):
|
||||
`to_be_*` and `to_have_count` failed, whatever the page held
|
||||
(2026-10-12). Polling is the server's, and so is the verdict:
|
||||
`isNot` inverts it, and a condition that never held is
|
||||
`ExpectNotMet` with the last value seen."""
|
||||
`ExpectNotMet` with the last value seen.
|
||||
|
||||
⛔ AND WHAT IS POLLED IS PLAYWRIGHT'S OWN READING ([B328]). Until 0.38
|
||||
this file re-wrote the conditions one by one, in Python, and had
|
||||
written two families: `to.have.count` and the `to.be.*` states.
|
||||
Everything else - `to_have_text`, `to_have_value`, `to_have_attribute`,
|
||||
`to_have_class`, `to_be_in_viewport`, `to_have_title`, `to_have_url`,
|
||||
`to_be_focused`, `to_be_empty`, `to_have_js_property`, `to_have_values`
|
||||
and the rest - answered "is not implemented yet", and Playwright's own
|
||||
suite was red on every one of them. The injected script this package
|
||||
already ships carries Playwright's `expect`, every condition of it, so
|
||||
the reading is that one function, called the way Playwright's server
|
||||
calls it (`_expectInternal` in `frames.ts`), and there is no second
|
||||
definition to fall behind. What stays here is what is the server's
|
||||
there too: the polling, the strict check, and the verdict.
|
||||
|
||||
A JavaScript error in the reading - a strict-mode violation, a
|
||||
`to_have_values` on something that is not a multiple select - ends the
|
||||
wait at once and travels as the message, as upstream: it is not a
|
||||
condition that a later page could make hold.
|
||||
"""
|
||||
expression = params.get("expression") or ""
|
||||
selector = params.get("selector")
|
||||
is_not = bool(params.get("isNot"))
|
||||
deadline = Deadline(self._timeout(params))
|
||||
last: Optional[Dict] = None
|
||||
while True:
|
||||
matches, received = self._expect_probe(expression, selector, params)
|
||||
if matches != is_not:
|
||||
return None
|
||||
try:
|
||||
reading = self._expect_probe(expression, selector, params)
|
||||
except ContextDestroyed:
|
||||
# A navigation under the reading: the next turn asks the new
|
||||
# document, as Playwright's polling survives one.
|
||||
reading = None
|
||||
except EvaluationError as e:
|
||||
message = str(e).split("\n", 1)[0]
|
||||
if message.startswith("Error: "):
|
||||
message = message[len("Error: "):]
|
||||
raise ExpectNotMet(message, {"customErrorMessage": message})
|
||||
if reading is not None:
|
||||
if reading["matches"] != is_not:
|
||||
return None
|
||||
last = reading
|
||||
if deadline.passed():
|
||||
details: Dict[str, Any] = {"timedOut": True}
|
||||
if last is not None:
|
||||
received: Dict[str, Any] = {}
|
||||
if "received" in last:
|
||||
received["value"] = _serialize(last["received"])
|
||||
if last.get("ariaSnapshot") is not None:
|
||||
received["ariaSnapshot"] = last["ariaSnapshot"]
|
||||
if received:
|
||||
details["received"] = received
|
||||
if last.get("missingReceived"):
|
||||
details["customErrorMessage"] = "element(s) not found"
|
||||
raise ExpectNotMet(
|
||||
"expect(%s%s) did not hold within %dms"
|
||||
% ("not " if is_not else "", expression,
|
||||
round(deadline.seconds * 1000)),
|
||||
{"received": {"value": _serialize(received)},
|
||||
"timedOut": True})
|
||||
details)
|
||||
time.sleep(deadline.slice(0.1))
|
||||
|
||||
#: What Playwright's server hands the injected `expect` of the caller's
|
||||
#: options. `expectedValue` is added parsed, as its dispatcher does.
|
||||
_EXPECT_OPTIONS = ("expression", "expressionArg", "expectedText",
|
||||
"expectedNumber", "useInnerText", "isNot", "selector")
|
||||
|
||||
#: One reading, as `_expectInternal` makes it: every element the selector
|
||||
#: matches, refused when a single-element condition matches more than one,
|
||||
#: and the first match handed to the injected script's `expect`.
|
||||
#: ⛔ `to.have.property` reads THE PAGE'S property: upstream sends that one
|
||||
#: condition to the main world, where the page's own expandos live. From
|
||||
#: this world the same object is `wrappedJSObject`, the page's view of the
|
||||
#: node, and every other condition stays on the native one.
|
||||
_EXPECT = (
|
||||
"async (injected, sel, options) => {"
|
||||
" let elements = [];"
|
||||
" if (sel !== null) {"
|
||||
" const parsed = injected.parseSelector(sel);"
|
||||
" elements = injected.querySelectorAll(parsed, document);"
|
||||
" const isArray = options.expression === 'to.have.count'"
|
||||
" || options.expression.endsWith('.array');"
|
||||
" if (!isArray && elements.length > 1)"
|
||||
" throw injected.strictModeViolationError(parsed, elements);"
|
||||
" }"
|
||||
" let element = elements[0];"
|
||||
" if (options.expression === 'to.have.property' && element"
|
||||
" && element.wrappedJSObject)"
|
||||
" element = element.wrappedJSObject;"
|
||||
" const r = await injected.expect(element, options, elements);"
|
||||
" const out = { matches: !!r.matches,"
|
||||
" missingReceived: !!r.missingReceived };"
|
||||
" if (r.received) {"
|
||||
" out.received = r.received.value === undefined ? null : r.received.value;"
|
||||
" if (r.received.ariaSnapshot !== undefined)"
|
||||
" out.ariaSnapshot = r.received.ariaSnapshot;"
|
||||
" }"
|
||||
" return out; }")
|
||||
|
||||
@staticmethod
|
||||
def _structured(argument: Any) -> bool:
|
||||
"""Whether Playwright's serialized argument is an object, an array, a
|
||||
date, a regular expression, a URL, an error, a typed array or a handle:
|
||||
anything that is not a primitive."""
|
||||
value = argument.get("value") if isinstance(argument, dict) else None
|
||||
return isinstance(value, dict) and any(
|
||||
tag in value for tag in ("o", "a", "d", "r", "u", "e", "ta", "h"))
|
||||
|
||||
def _expect_probe(self, expression: str, selector: Optional[str],
|
||||
params: Dict) -> tuple:
|
||||
params: Dict) -> Dict:
|
||||
"""One reading of an expect condition, on the page as it is NOW:
|
||||
`(matches, received)`."""
|
||||
if selector and expression == "to.have.count":
|
||||
frame_id, sel = self.enter_frames(selector)
|
||||
count = self.injected.count(frame_id, sel)
|
||||
return count == params.get("expectedNumber"), count
|
||||
if selector and expression.startswith("to.be."):
|
||||
return self._expect_state(expression[len("to.be."):], selector,
|
||||
params)
|
||||
raise ProtocolException(
|
||||
"expect(%r) is not implemented yet" % expression)
|
||||
`{matches, received?, ariaSnapshot?, missingReceived}`.
|
||||
|
||||
def _expect_state(self, name: str, selector: str, params: Dict) -> tuple:
|
||||
"""`to.be.<name>` on the element as it is now: `(matches, received)`.
|
||||
|
||||
⛔ UNTIL 0.34.1 THE STATE WAS READ INTO A VARIABLE NOBODY USED, and any
|
||||
element that existed matched: `to_be_checked()` on an empty box,
|
||||
`to_be_visible()` on a hidden element. Each state is now the
|
||||
element's, read with the match in one command (`read_match`), and a
|
||||
missing element is hidden and nothing else, as in Playwright."""
|
||||
frame_id, sel = self.enter_frames(selector)
|
||||
if name in ("attached", "detached"):
|
||||
found = self.injected.count(frame_id, sel) > 0
|
||||
return found == (name == "attached"), found
|
||||
if name == "checked":
|
||||
wanted = _deserialize(params.get("expectedValue")) or {}
|
||||
if wanted.get("indeterminate"):
|
||||
state = "indeterminate"
|
||||
else:
|
||||
state = ("unchecked" if wanted.get("checked") is False
|
||||
else "checked")
|
||||
invert = False
|
||||
elif name == "readonly":
|
||||
state, invert = "editable", True
|
||||
elif name in ("visible", "hidden", "enabled", "disabled", "editable"):
|
||||
state, invert = name, False
|
||||
else:
|
||||
⛔ `to.match.aria` IS REFUSED BY NAME: its template is YAML that
|
||||
Playwright's server parses into a tree before the injected script sees
|
||||
it, and this server has no parser for it. Saying so is the honest
|
||||
answer; matching an unparsed string would be a verdict on nothing."""
|
||||
if expression == "to.match.aria":
|
||||
raise ProtocolException(
|
||||
"expect(%r) is not implemented yet" % ("to.be." + name))
|
||||
found, value = self.injected.read_match(frame_id, sel, "state", state,
|
||||
strict=True)
|
||||
if not found:
|
||||
return state == "hidden", None
|
||||
return bool(value) != invert, bool(value)
|
||||
"expect('to.match.aria') is not implemented yet: the template is "
|
||||
"YAML that Playwright's server parses, and this one has no parser "
|
||||
"for it")
|
||||
if expression == "to.have.property" and self._structured(params.get("expectedValue")):
|
||||
# ⛔ A FALSE "DIFFERENT" IS WORSE THAN A REFUSAL. Upstream compares in
|
||||
# the page's own realm; here the page's value is read from the
|
||||
# utility world, and Playwright's `deepEquals` refuses two objects
|
||||
# whose constructors are not the same one, which across realms they
|
||||
# never are. A primitive compares by value and is answered.
|
||||
raise ProtocolException(
|
||||
"expect('to.have.property') with an object, an array or a date "
|
||||
"as the expected value is not implemented yet: the page's value "
|
||||
"lives in another realm, and comparing it would always say it "
|
||||
"differs. A primitive value is compared.")
|
||||
if selector:
|
||||
frame_id, sel = self.enter_frames(selector)
|
||||
else:
|
||||
frame_id, sel = self.frame_id, None
|
||||
options = {k: params[k] for k in self._EXPECT_OPTIONS if k in params}
|
||||
if params.get("expectedValue") is not None:
|
||||
options["expectedValue"] = _deserialize(params["expectedValue"])
|
||||
return self.injected.call(frame_id, self._EXPECT, sel, options) or {
|
||||
"matches": False, "missingReceived": True}
|
||||
|
||||
def op_aria_snapshot(self, params: Dict) -> Any:
|
||||
"""The accessibility tree, as the injected script builds it.
|
||||
|
||||
@@ -310,8 +310,18 @@ def test_frames_reach_the_client_from_the_lifecycle_alone(page):
|
||||
assert attached[0]["params"]["frame"]["guid"] == page._frames["fresh"].guid
|
||||
|
||||
|
||||
def _reading(matches, received=None, **more):
|
||||
"""One reading as the injected script's `expect` answers it."""
|
||||
out = {"matches": matches, "missingReceived": False}
|
||||
if received is not None:
|
||||
out["received"] = received
|
||||
out.update(more)
|
||||
return out
|
||||
|
||||
|
||||
def test_expect_polls_until_the_condition_holds(page):
|
||||
page.frame._expect_probe = Mock(side_effect=[(False, 0), (False, 1), (True, 2)])
|
||||
page.frame._expect_probe = Mock(side_effect=[_reading(False, 0), _reading(False, 1),
|
||||
_reading(True, 2)])
|
||||
assert page.frame.op_expect({"expression": "to.have.count", "selector": "x",
|
||||
"timeout": 5000}) is None
|
||||
assert page.frame._expect_probe.call_count == 3
|
||||
@@ -320,16 +330,127 @@ def test_expect_polls_until_the_condition_holds(page):
|
||||
def test_expect_not_inverts_and_a_condition_that_never_holds_carries_details(page):
|
||||
from invisible_playwright._juggler.dispatcher import ExpectNotMet
|
||||
|
||||
page.frame._expect_probe = Mock(return_value=(True, True))
|
||||
page.frame._expect_probe = Mock(return_value=_reading(True, "checked"))
|
||||
with pytest.raises(ExpectNotMet) as caught:
|
||||
page.frame.op_expect({"expression": "to.be.checked", "selector": "x",
|
||||
"isNot": True, "timeout": 300})
|
||||
assert caught.value.details == {"received": {"value": {"b": True}},
|
||||
assert caught.value.details == {"received": {"value": {"s": "checked"}},
|
||||
"timedOut": True}
|
||||
assert page.frame.op_expect({"expression": "to.be.checked", "selector": "x",
|
||||
"isNot": False, "timeout": 300}) is None
|
||||
|
||||
|
||||
def test_a_missing_element_says_so_as_playwright_does(page):
|
||||
"""`element(s) not found` is the message upstream's server writes when the
|
||||
reading says nothing matched, and the aria snapshot of the page travels
|
||||
with the last value, for the error the client renders."""
|
||||
from invisible_playwright._juggler.dispatcher import ExpectNotMet
|
||||
|
||||
page.frame._expect_probe = Mock(return_value={
|
||||
"matches": False, "missingReceived": True, "ariaSnapshot": "- main"})
|
||||
with pytest.raises(ExpectNotMet) as caught:
|
||||
page.frame.op_expect({"expression": "to.have.text", "selector": "#nope",
|
||||
"timeout": 200})
|
||||
assert caught.value.details == {"received": {"ariaSnapshot": "- main"},
|
||||
"customErrorMessage": "element(s) not found",
|
||||
"timedOut": True}
|
||||
|
||||
|
||||
def test_a_javascript_error_in_the_reading_ends_the_wait_with_its_message(page):
|
||||
"""A strict-mode violation cannot start to hold later: upstream raises it at
|
||||
once as the message, and so does this, without spending the timeout."""
|
||||
import time as _time
|
||||
|
||||
from invisible_core.juggler.injected import EvaluationError
|
||||
from invisible_playwright._juggler.dispatcher import ExpectNotMet
|
||||
|
||||
page.frame._expect_probe = Mock(side_effect=EvaluationError(
|
||||
"Error: strict mode violation: locator('button') resolved to 2 elements\n"
|
||||
" at strictModeViolationError"))
|
||||
started = _time.monotonic()
|
||||
with pytest.raises(ExpectNotMet) as caught:
|
||||
page.frame.op_expect({"expression": "to.have.text", "selector": "button",
|
||||
"timeout": 5000})
|
||||
assert _time.monotonic() - started < 2
|
||||
assert caught.value.details == {
|
||||
"customErrorMessage": "strict mode violation: locator('button') resolved to 2 elements"}
|
||||
assert page.frame._expect_probe.call_count == 1
|
||||
|
||||
|
||||
def test_a_navigation_under_the_reading_is_read_again(page):
|
||||
from invisible_core.juggler.injected import ContextDestroyed
|
||||
|
||||
page.frame._expect_probe = Mock(side_effect=[ContextDestroyed("gone"), _reading(True, "x")])
|
||||
assert page.frame.op_expect({"expression": "to.have.text", "selector": "p",
|
||||
"timeout": 5000}) is None
|
||||
assert page.frame._expect_probe.call_count == 2
|
||||
|
||||
|
||||
def test_the_reading_is_the_injected_scripts_expect_with_playwrights_options(page):
|
||||
"""The options the caller sent, as upstream hands them over: `expectedValue`
|
||||
parsed, everything else as it came, and the page-level conditions with no
|
||||
selector at all."""
|
||||
calls = []
|
||||
|
||||
def call(frame_id, declaration, sel, options):
|
||||
calls.append((frame_id, declaration, sel, options))
|
||||
return {"matches": True, "missingReceived": False}
|
||||
|
||||
page.injected = Mock()
|
||||
page.injected.call = call
|
||||
page.frame.enter_frames = lambda selector: ("main", selector)
|
||||
page.frame._expect_probe("to.have.property", "#x", {
|
||||
"expression": "to.have.property", "expressionArg": "a.b", "selector": "#x",
|
||||
"expectedValue": {"value": {"n": 3}, "handles": []}, "isNot": False,
|
||||
"timeout": 1000})
|
||||
page.frame._expect_probe("to.have.title", None, {
|
||||
"expression": "to.have.title", "isNot": False,
|
||||
"expectedText": [{"string": "T", "matchSubstring": False}]})
|
||||
(_, declaration, sel, options), (_, _, sel2, options2) = calls
|
||||
assert "injected.expect(element, options, elements)" in declaration
|
||||
assert "strictModeViolationError" in declaration
|
||||
assert sel == "#x" and options == {
|
||||
"expression": "to.have.property", "expressionArg": "a.b", "selector": "#x",
|
||||
"isNot": False, "expectedValue": 3}
|
||||
assert sel2 is None and options2["expectedText"] == [{"string": "T", "matchSubstring": False}]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [
|
||||
{"o": [{"k": "a", "v": {"n": 1}}], "id": 1},
|
||||
{"a": [{"n": 1}], "id": 1},
|
||||
{"d": "2021-07-28T20:26:32.000Z"},
|
||||
{"r": {"p": "x", "f": ""}},
|
||||
])
|
||||
def test_a_structured_js_property_is_refused_rather_than_called_different(page, value):
|
||||
"""Across realms Playwright's `deepEquals` calls two equal objects different;
|
||||
the refusal says so instead of failing an assertion that holds."""
|
||||
from invisible_playwright._juggler.dispatcher import ProtocolException
|
||||
|
||||
page.injected = Mock()
|
||||
with pytest.raises(ProtocolException, match="another realm"):
|
||||
page.frame._expect_probe("to.have.property", "div", {
|
||||
"expression": "to.have.property", "expressionArg": "foo",
|
||||
"expectedValue": {"value": value, "handles": []}})
|
||||
assert not page.injected.call.called
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [{"n": 3}, {"s": "x"}, {"b": True}, {"v": "null"}])
|
||||
def test_a_primitive_js_property_is_compared(page, value):
|
||||
page.injected = Mock()
|
||||
page.injected.call = Mock(return_value={"matches": True, "missingReceived": False})
|
||||
page.frame.enter_frames = lambda selector: ("main", selector)
|
||||
assert page.frame._expect_probe("to.have.property", "div", {
|
||||
"expression": "to.have.property", "expressionArg": "foo",
|
||||
"expectedValue": {"value": value, "handles": []}})["matches"] is True
|
||||
|
||||
|
||||
def test_to_match_aria_is_refused_by_name(page):
|
||||
from invisible_playwright._juggler.dispatcher import ProtocolException
|
||||
|
||||
with pytest.raises(ProtocolException, match="to.match.aria"):
|
||||
page.frame._expect_probe("to.match.aria", "main", {"expression": "to.match.aria"})
|
||||
|
||||
|
||||
def test_an_error_with_details_sends_them_where_the_client_reads_them():
|
||||
from invisible_playwright._juggler.dispatcher import ExpectNotMet
|
||||
from invisible_playwright._juggler.transport import InProcessTransport
|
||||
|
||||
Reference in new issue
Block a user