From 69f49169ffe26b909406814c9e128bc1c10b8b34 Mon Sep 17 00:00:00 2001 From: "microsoft-playwright-automation[bot]" <203992400+microsoft-playwright-automation[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:59:07 +0000 Subject: [PATCH 1/2] fix(events): preserve pytest outcomes without closing the connection Fixes: https://github.com/microsoft/playwright-python/issues/3360 --- playwright/_impl/event_emitter.py | 12 +++++++++--- playwright/_impl/out_of_process.py | 8 ++++++-- playwright/_impl/utils/tasks.py | 11 +++++++++++ tests/sync/python/test_sync.py | 19 +++++++++++++++++++ 4 files changed, 45 insertions(+), 5 deletions(-) diff --git a/playwright/_impl/event_emitter.py b/playwright/_impl/event_emitter.py index f09b69275..15658e6c6 100644 --- a/playwright/_impl/event_emitter.py +++ b/playwright/_impl/event_emitter.py @@ -28,7 +28,7 @@ from typing import Any, Callable, Dict, List, Optional, Set, Union from playwright._impl.utils.debug import is_under_test -from playwright._impl.utils.tasks import completed +from playwright._impl.utils.tasks import CONTROL_FLOW_EXCEPTIONS, completed EventType = str Listener = Callable[..., Any] @@ -88,7 +88,11 @@ def _call_handler(self, type: EventType, handler: Listener, args: Any) -> None: return # Python: an awaitable is the counterpart of a JS promise or thenable. future = asyncio.ensure_future(promise) - except Exception as error: + # Python: pytest outcomes inherit BaseException, but cancellation and exits + # must not be treated as listener errors. + except CONTROL_FLOW_EXCEPTIONS: + raise + except BaseException as error: self._handle_listener_error(type, error) return pending = self._pending_handlers.get(type) @@ -109,7 +113,9 @@ def on_done(f: "asyncio.Future[Any]") -> None: else: try: self._handle_listener_error(type, e) - except Exception as error: + except CONTROL_FLOW_EXCEPTIONS: + raise + except BaseException as error: # Python: report an unhandled rejection outside the task callback. self._report_unhandled_error(error) diff --git a/playwright/_impl/out_of_process.py b/playwright/_impl/out_of_process.py index 212f878a5..086876efa 100644 --- a/playwright/_impl/out_of_process.py +++ b/playwright/_impl/out_of_process.py @@ -26,6 +26,7 @@ from playwright._impl.connection import Connection from playwright._impl.playwright import Playwright from playwright._impl.transport import PipeTransport +from playwright._impl.utils.tasks import CONTROL_FLOW_EXCEPTIONS async def start() -> Tuple[Playwright, "PlaywrightClient"]: @@ -47,10 +48,13 @@ def __init__(self, dispatcher_fiber: Any = None) -> None: def on_message(message: Any) -> None: # Python: an exception in a listener crashes Node.js; here the next API - # call raises it, and the transport goes on. + # call raises it, and the transport goes on, also for pytest outcomes. + # Cancellation and exits still pass through. try: connection.dispatch(message) - except Exception as error: + except CONTROL_FLOW_EXCEPTIONS: + raise + except BaseException as error: connection._on_event_listener_error(error) transport.on_message = on_message diff --git a/playwright/_impl/utils/tasks.py b/playwright/_impl/utils/tasks.py index 6d420d5d0..e730559fc 100644 --- a/playwright/_impl/utils/tasks.py +++ b/playwright/_impl/utils/tasks.py @@ -24,8 +24,19 @@ import asyncio from typing import Any, Awaitable, Callable, List, Sequence, Set, TypeVar +from greenlet import GreenletExit + T = TypeVar("T") +# Python only: these stop execution, unlike user errors such as pytest.fail(). +CONTROL_FLOW_EXCEPTIONS = ( + KeyboardInterrupt, + SystemExit, + GeneratorExit, + asyncio.CancelledError, + GreenletExit, +) + # The tasks of fire_and_forget(): the event loop keeps only weak references. _tasks: Set["asyncio.Future[Any]"] = set() diff --git a/tests/sync/python/test_sync.py b/tests/sync/python/test_sync.py index c6bec2941..b90581004 100644 --- a/tests/sync/python/test_sync.py +++ b/tests/sync/python/test_sync.py @@ -87,6 +87,7 @@ def on_dialog(dialog: Dialog) -> None: def test_console_repr(page: Page) -> None: + # Regression test for https://github.com/microsoft/playwright-python/issues/3360. # Regression test for https://github.com/microsoft/playwright-python/issues/3340. messages: List[ConsoleMessage] = [] page.on("console", messages.append) @@ -104,6 +105,24 @@ def test_console_repr(page: Page) -> None: assert [m.text for m in once_messages] == ["once"] assert messages == [message] + def fail_console(message: ConsoleMessage) -> None: + pytest.fail(f"console: {message.text}") + + errors: List[BaseException] = [] + page._impl_obj.on("error", errors.append) + page.on("console", fail_console) + page.evaluate("console.log('handled')") + assert len(errors) == 1 + assert isinstance(errors[0], pytest.fail.Exception) + assert str(errors[0]) == "console: handled" + + page._impl_obj.remove_listener("error", errors.append) + page.evaluate("console.log('unhandled')") + with pytest.raises(pytest.fail.Exception, match="console: unhandled"): + page.evaluate("1 + 1") + page.remove_listener("console", fail_console) + assert page.evaluate("1 + 1") == 2 + def test_sync_wait_for_event_raise(page: Page) -> None: with pytest.raises(AssertionError): From 3c82bc5b2747c3d06eea9b2effbd3cba9b568ac4 Mon Sep 17 00:00:00 2001 From: "microsoft-playwright-automation[bot]" <203992400+microsoft-playwright-automation[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:15:52 +0000 Subject: [PATCH 2/2] fix(events): forward only supported listener exceptions --- playwright/_impl/_errors.py | 18 +++++++++++++++++- playwright/_impl/event_emitter.py | 14 +++++--------- playwright/_impl/out_of_process.py | 7 ++----- playwright/_impl/utils/tasks.py | 11 ----------- tests/sync/python/test_sync.py | 10 ++++++++++ 5 files changed, 34 insertions(+), 26 deletions(-) diff --git a/playwright/_impl/_errors.py b/playwright/_impl/_errors.py index ced1211ff..76f9fd8b2 100644 --- a/playwright/_impl/_errors.py +++ b/playwright/_impl/_errors.py @@ -19,7 +19,23 @@ packages/playwright-core/src/client/errors.ts. """ -from typing import Any, List, Optional +import sys +from typing import Any, List, Optional, Tuple, Type + + +def listener_error_types() -> Tuple[Type[BaseException], ...]: + """Errors to forward from listeners, including pytest's supported outcomes.""" + # Do not import pytest in applications that do not use it. Look it up at the + # catch site so importing pytest after Playwright also works. + pytest = sys.modules.get("pytest") + if pytest is None: + return (Exception,) + return ( + Exception, + pytest.fail.Exception, + pytest.skip.Exception, + pytest.xfail.Exception, + ) class Error(Exception): diff --git a/playwright/_impl/event_emitter.py b/playwright/_impl/event_emitter.py index 15658e6c6..2b16c3fba 100644 --- a/playwright/_impl/event_emitter.py +++ b/playwright/_impl/event_emitter.py @@ -27,8 +27,9 @@ import sys from typing import Any, Callable, Dict, List, Optional, Set, Union +from playwright._impl._errors import listener_error_types from playwright._impl.utils.debug import is_under_test -from playwright._impl.utils.tasks import CONTROL_FLOW_EXCEPTIONS, completed +from playwright._impl.utils.tasks import completed EventType = str Listener = Callable[..., Any] @@ -88,11 +89,8 @@ def _call_handler(self, type: EventType, handler: Listener, args: Any) -> None: return # Python: an awaitable is the counterpart of a JS promise or thenable. future = asyncio.ensure_future(promise) - # Python: pytest outcomes inherit BaseException, but cancellation and exits - # must not be treated as listener errors. - except CONTROL_FLOW_EXCEPTIONS: - raise - except BaseException as error: + # Python: also forward pytest outcomes, which do not inherit Exception. + except listener_error_types() as error: self._handle_listener_error(type, error) return pending = self._pending_handlers.get(type) @@ -113,9 +111,7 @@ def on_done(f: "asyncio.Future[Any]") -> None: else: try: self._handle_listener_error(type, e) - except CONTROL_FLOW_EXCEPTIONS: - raise - except BaseException as error: + except listener_error_types() as error: # Python: report an unhandled rejection outside the task callback. self._report_unhandled_error(error) diff --git a/playwright/_impl/out_of_process.py b/playwright/_impl/out_of_process.py index 086876efa..5dc6bd194 100644 --- a/playwright/_impl/out_of_process.py +++ b/playwright/_impl/out_of_process.py @@ -23,10 +23,10 @@ import asyncio from typing import Any, Tuple +from playwright._impl._errors import listener_error_types from playwright._impl.connection import Connection from playwright._impl.playwright import Playwright from playwright._impl.transport import PipeTransport -from playwright._impl.utils.tasks import CONTROL_FLOW_EXCEPTIONS async def start() -> Tuple[Playwright, "PlaywrightClient"]: @@ -49,12 +49,9 @@ def __init__(self, dispatcher_fiber: Any = None) -> None: def on_message(message: Any) -> None: # Python: an exception in a listener crashes Node.js; here the next API # call raises it, and the transport goes on, also for pytest outcomes. - # Cancellation and exits still pass through. try: connection.dispatch(message) - except CONTROL_FLOW_EXCEPTIONS: - raise - except BaseException as error: + except listener_error_types() as error: connection._on_event_listener_error(error) transport.on_message = on_message diff --git a/playwright/_impl/utils/tasks.py b/playwright/_impl/utils/tasks.py index e730559fc..6d420d5d0 100644 --- a/playwright/_impl/utils/tasks.py +++ b/playwright/_impl/utils/tasks.py @@ -24,19 +24,8 @@ import asyncio from typing import Any, Awaitable, Callable, List, Sequence, Set, TypeVar -from greenlet import GreenletExit - T = TypeVar("T") -# Python only: these stop execution, unlike user errors such as pytest.fail(). -CONTROL_FLOW_EXCEPTIONS = ( - KeyboardInterrupt, - SystemExit, - GeneratorExit, - asyncio.CancelledError, - GreenletExit, -) - # The tasks of fire_and_forget(): the event loop keeps only weak references. _tasks: Set["asyncio.Future[Any]"] = set() diff --git a/tests/sync/python/test_sync.py b/tests/sync/python/test_sync.py index b90581004..f2e57e898 100644 --- a/tests/sync/python/test_sync.py +++ b/tests/sync/python/test_sync.py @@ -123,6 +123,16 @@ def fail_console(message: ConsoleMessage) -> None: page.remove_listener("console", fail_console) assert page.evaluate("1 + 1") == 2 + def interrupt_console(message: ConsoleMessage) -> None: + raise Interrupted("not a pytest outcome") + + page._impl_obj.on("error", errors.append) + page.on("console", interrupt_console) + with pytest.raises(Interrupted, match="not a pytest outcome"): + page._impl_obj.emit("console", message._impl_obj) + assert len(errors) == 1 + page.remove_listener("console", interrupt_console) + def test_sync_wait_for_event_raise(page: Page) -> None: with pytest.raises(AssertionError):