diff --git a/playwright/_impl/_greenlets.py b/playwright/_impl/_greenlets.py index c5b3fd4dd..b4727c0c5 100644 --- a/playwright/_impl/_greenlets.py +++ b/playwright/_impl/_greenlets.py @@ -18,6 +18,7 @@ import greenlet from playwright._impl._errors import TargetClosedError +from playwright._impl.utils.tasks import CONTROL_FLOW_EXCEPTIONS def _greenlet_trace_callback( @@ -80,7 +81,9 @@ def run_in_greenlet( def body() -> None: try: future.set_result(func()) - except Exception as e: + except CONTROL_FLOW_EXCEPTIONS: + raise + except BaseException as e: future.set_exception(e) greenlet_class(body).switch() diff --git a/playwright/_impl/channel_owner.py b/playwright/_impl/channel_owner.py index 0412582ae..3262fd175 100644 --- a/playwright/_impl/channel_owner.py +++ b/playwright/_impl/channel_owner.py @@ -53,7 +53,11 @@ show_internal_stack_frames, stringify_stack_frames, ) -from playwright._impl.utils.tasks import failed, fire_and_forget +from playwright._impl.utils.tasks import ( + CONTROL_FLOW_EXCEPTIONS, + failed, + fire_and_forget, +) from playwright._impl.utils.zones import current_zone if TYPE_CHECKING: # pragma: no cover @@ -80,7 +84,7 @@ def __init__( self.reported = False self.user_data: Any = None self.call_id: Optional[str] = None - self.error: Optional[Exception] = None + self.error: Optional[BaseException] = None def options(self) -> Dict[str, Any]: # Python: `{ ...apiZone }` in the options of sendMessageToServer(). @@ -157,7 +161,9 @@ def func(api_zone: ApiZone) -> Awaitable[Any]: # option, which is enough. try: result = owner._wrap_api_call(func, ApiCallOptions(internal=is_internal)) - except Exception as e: + except CONTROL_FLOW_EXCEPTIONS: + raise + except BaseException as e: return failed(e) if mapper is None: return result @@ -354,14 +360,14 @@ async def finish() -> R: log_api_call(logger, f"<= {api_zone.api_name} succeeded") self._instrumentation.on_api_call_end(api_zone) return result - except asyncio.CancelledError: + except CONTROL_FLOW_EXCEPTIONS: # Python: the task that awaits the call was cancelled, and the call # is aborted; upstream sees an AbortError. if not (options and options.internal): log_api_call(logger, f"<= {api_zone.api_name} failed") self._instrumentation.on_api_call_end(api_zone) raise - except Exception as e: + except BaseException as e: stack = getattr(e, "_stack", None) inner_error = ( "\n\n" + stack diff --git a/playwright/_impl/connect.py b/playwright/_impl/connect.py index 0c8f313e6..d8e4adb04 100644 --- a/playwright/_impl/connect.py +++ b/playwright/_impl/connect.py @@ -50,7 +50,11 @@ from playwright._impl.isomorphic.string_utils import js_string from playwright._impl.isomorphic.time import monotonic_time from playwright._impl.timeout_settings import NO_TIMEOUT -from playwright._impl.utils.tasks import call_in_next_task, fire_and_forget +from playwright._impl.utils.tasks import ( + CONTROL_FLOW_EXCEPTIONS, + call_in_next_task, + fire_and_forget, +) if TYPE_CHECKING: # pragma: no cover from playwright._impl.local_utils import LocalUtils @@ -164,7 +168,9 @@ def on_message(message: Dict[str, Any]) -> None: nonlocal close_error try: connection.dispatch(message) - except Exception as e: + except CONTROL_FLOW_EXCEPTIONS: + raise + except BaseException as e: # Python: String(e) is the name and the message of the error. close_error = f"{e.name if isinstance(e, Error) else type(e).__name__}: {e}" fire_and_forget(transport.close()) diff --git a/playwright/_impl/connection.py b/playwright/_impl/connection.py index 6c387f940..94a0080d5 100644 --- a/playwright/_impl/connection.py +++ b/playwright/_impl/connection.py @@ -44,7 +44,6 @@ ) from playwright._impl.errors import ( Error, - PlaywrightError, TargetClosedError, parse_error, ) @@ -319,11 +318,8 @@ def dispatch(self, message: Dict[str, Any]) -> None: if error and not result: parsed_error = parse_error(error) parsed_error._log = log or [] - parsed_error = cast( - PlaywrightError, - rewrite_error_message( - parsed_error, parsed_error.message + format_call_log(log) - ), + parsed_error = rewrite_error_message( + parsed_error, parsed_error.message + format_call_log(log) ) details_validator = maybe_find_validator( callback.type, callback.method, "ErrorDetails" diff --git a/playwright/_impl/event_emitter.py b/playwright/_impl/event_emitter.py index f09b69275..328c070e7 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,9 @@ 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: + except CONTROL_FLOW_EXCEPTIONS: + raise + except BaseException as error: self._handle_listener_error(type, error) return pending = self._pending_handlers.get(type) @@ -109,7 +111,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/network.py b/playwright/_impl/network.py index 1b65871a8..bc278ef7a 100644 --- a/playwright/_impl/network.py +++ b/playwright/_impl/network.py @@ -83,7 +83,11 @@ ) from playwright._impl.timeout_settings import NO_TIMEOUT from playwright._impl.utils.stack_trace import rewrite_error_message -from playwright._impl.utils.tasks import completed, fire_and_forget +from playwright._impl.utils.tasks import ( + CONTROL_FLOW_EXCEPTIONS, + completed, + fire_and_forget, +) from playwright._impl.utils.zones import Zone, current_zone from playwright._impl.waiter import Waiter @@ -1276,7 +1280,9 @@ async def _handle_impl(self, route: Route) -> bool: self._active_invocations.add(handler_invocation) try: return await self._handle_internal(route) - except Exception as e: + except CONTROL_FLOW_EXCEPTIONS: + raise + except BaseException as e: # If the handler was stopped (without waiting for completion), we ignore all exceptions. if self._ignore_exception: return False diff --git a/playwright/_impl/out_of_process.py b/playwright/_impl/out_of_process.py index 212f878a5..08838b9a2 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"]: @@ -50,7 +51,9 @@ def on_message(message: Any) -> None: # call raises it, and the transport goes on. 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/page.py b/playwright/_impl/page.py index 6e6bb55ef..20cc726ff 100644 --- a/playwright/_impl/page.py +++ b/playwright/_impl/page.py @@ -118,7 +118,7 @@ ) from playwright._impl.screencast import Screencast from playwright._impl.timeout_settings import NO_TIMEOUT, TimeoutSettings -from playwright._impl.utils.tasks import fire_and_forget +from playwright._impl.utils.tasks import CONTROL_FLOW_EXCEPTIONS, fire_and_forget from playwright._impl.video import Video from playwright._impl.waiter import Waiter from playwright._impl.web_storage import WebStorage @@ -1882,7 +1882,9 @@ async def call(self, func: Callable[..., Any]) -> None: result=serialize_argument(_to_impl(result)), timeout=NO_TIMEOUT ) ) - except Exception as e: + except CONTROL_FLOW_EXCEPTIONS: + raise + except BaseException as e: fire_and_forget( self._channel.reject(error=serialize_error(e), timeout=NO_TIMEOUT) ) diff --git a/playwright/_impl/utils/stack_trace.py b/playwright/_impl/utils/stack_trace.py index f04103bae..9f5521ca0 100644 --- a/playwright/_impl/utils/stack_trace.py +++ b/playwright/_impl/utils/stack_trace.py @@ -26,12 +26,14 @@ import sys import sysconfig from types import FrameType -from typing import List, Optional, Tuple, TypedDict +from typing import List, Optional, Tuple, TypedDict, TypeVar import playwright from playwright._impl.errors import Error from playwright._impl.utils.debug import get_as_boolean_from_env +E = TypeVar("E", bound=BaseException) + class StackFrame(TypedDict, total=False): file: str @@ -71,7 +73,7 @@ def _sync_caller_frame() -> Optional[FrameType]: return getattr(task, "__pw_caller_frame__", None) -def rewrite_error_message(e: Exception, new_message: str) -> Exception: +def rewrite_error_message(e: E, new_message: str) -> E: """Port of rewriteErrorMessage(). Python: upstream changes the error itself; this changes a copy, because the same diff --git a/playwright/_impl/utils/tasks.py b/playwright/_impl/utils/tasks.py index 6d420d5d0..f057c2991 100644 --- a/playwright/_impl/utils/tasks.py +++ b/playwright/_impl/utils/tasks.py @@ -24,8 +24,20 @@ import asyncio from typing import Any, Awaitable, Callable, List, Sequence, Set, TypeVar +from greenlet import GreenletExit + T = TypeVar("T") +# Control-flow BaseExceptions that must pass through untouched rather than +# being caught as listener or user-handler failures (unlike e.g. 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/playwright/_impl/waiter.py b/playwright/_impl/waiter.py index 0878dfe79..57180ceb9 100644 --- a/playwright/_impl/waiter.py +++ b/playwright/_impl/waiter.py @@ -34,7 +34,12 @@ from playwright._impl.errors import TimeoutError from playwright._impl.utils.crypto import create_guid from playwright._impl.utils.stack_trace import rewrite_error_message -from playwright._impl.utils.tasks import completed, fire_and_forget, race +from playwright._impl.utils.tasks import ( + CONTROL_FLOW_EXCEPTIONS, + completed, + fire_and_forget, + race, +) from playwright._impl.utils.zones import Zone, current_zone if TYPE_CHECKING: # pragma: no cover @@ -185,15 +190,16 @@ async def wait_for_promise( if dispose: dispose() return result - except asyncio.CancelledError: + except CONTROL_FLOW_EXCEPTIONS as e: # Python: the task that waits was cancelled, for example by an expect_*() # block that raised. Clean up as for an error. if dispose: dispose() - self._error = "The operation was aborted" + if isinstance(e, asyncio.CancelledError): + self._error = "The operation was aborted" self.dispose() raise - except Exception as e: + except BaseException as e: if dispose: dispose() self._error = str(e) @@ -240,7 +246,7 @@ def settle(matched: bool) -> None: if not promise.done(): promise.set_result(event_arg) - def fail(e: Exception) -> None: + def fail(e: BaseException) -> None: emitter.remove_listener(event, listener) if not promise.done(): promise.set_exception(e) @@ -256,13 +262,17 @@ def run() -> Any: async def continuation() -> None: try: settle(bool(await matched)) - except Exception as e: + except CONTROL_FLOW_EXCEPTIONS: + raise + except BaseException as e: fail(e) # Python: started here, so that it runs in the saved zone. return asyncio.ensure_future(continuation()) settle(bool(matched)) - except Exception as e: + except CONTROL_FLOW_EXCEPTIONS: + raise + except BaseException as e: fail(e) return None diff --git a/tests/async/python/test_listeners.py b/tests/async/python/test_listeners.py index fb22c42f5..62d6b8eae 100644 --- a/tests/async/python/test_listeners.py +++ b/tests/async/python/test_listeners.py @@ -14,7 +14,19 @@ """Python only: tests of behaviors that no upstream test covers.""" -from playwright.async_api import Page, Response +import asyncio +from typing import Any, List, cast + +import pytest + +from playwright.async_api import ( + BrowserContext, + ConsoleMessage, + Error, + Page, + Response, + Route, +) from tests.server import Server @@ -32,3 +44,80 @@ def print_response(response: Response) -> None: log = [] await page.goto(f"{server.PREFIX}/input/textarea.html") assert len(log) == 0 + + +async def test_listeners_preserve_base_exception( + context: BrowserContext, server: Server +) -> None: + # Regression test for https://github.com/microsoft/playwright-python/issues/3360. + page = await context.new_page() + + def fail_sync(msg: ConsoleMessage) -> None: + pytest.fail(f"sync: {msg.text}") + + try: + page.on("console", fail_sync) + await page.evaluate("console.log('hi')") + with pytest.raises(pytest.fail.Exception, match="sync: hi"): + await page.evaluate("1 + 1") + assert await page.evaluate("1 + 1") == 2 + + page.remove_listener("console", fail_sync) + + invoked = asyncio.Event() + + async def fail_async(msg: ConsoleMessage) -> None: + invoked.set() + pytest.fail(f"async: {msg.text}") + + page.on("console", fail_async) + await page.evaluate("console.log('coro')") + await asyncio.wait_for(invoked.wait(), timeout=5) + await asyncio.sleep(0) + with pytest.raises(pytest.fail.Exception, match="async: coro"): + await page.evaluate("1 + 1") + assert await page.evaluate("1 + 1") == 2 + + page.remove_listener("console", fail_async) + seen: List[BaseException] = [] + done = asyncio.Event() + + def on_error(err: BaseException) -> None: + seen.append(err) + done.set() + + cast(Any, page).on("error", on_error) + page.on("console", fail_async) + await page.evaluate("console.log('handled')") + await asyncio.wait_for(done.wait(), timeout=5) + assert len(seen) == 1 + assert isinstance(seen[0], pytest.fail.Exception) + assert "async: handled" in str(seen[0]) + assert await page.evaluate("1 + 1") == 2 + + page.remove_listener("console", fail_async) + cast(Any, page).remove_listener("error", on_error) + + async def fail_after_fulfill(route: Route) -> None: + await route.fulfill(body="ok") + pytest.fail("route failed") + + await page.route("**/empty.html", fail_after_fulfill) + await page.goto(server.EMPTY_PAGE) + with pytest.raises(pytest.fail.Exception, match="route failed"): + await page.evaluate("1 + 1") + await page.unroute("**/empty.html") + + with pytest.raises(pytest.fail.Exception, match="predicate: boom"): + async with page.expect_console_message( + lambda msg: pytest.fail(f"predicate: {msg.text}") + ): + await page.evaluate("console.log('boom')") + assert await page.evaluate("1 + 1") == 2 + + await page.expose_function("pwFail", lambda: pytest.fail("binding failed")) + with pytest.raises(Error, match="binding failed"): + await page.evaluate("window.pwFail()") + assert await page.evaluate("1 + 1") == 2 + finally: + await page.close() diff --git a/tests/sync/python/test_sync.py b/tests/sync/python/test_sync.py index c6bec2941..218b314e5 100644 --- a/tests/sync/python/test_sync.py +++ b/tests/sync/python/test_sync.py @@ -23,7 +23,7 @@ import time from datetime import timedelta from pathlib import Path -from typing import Any, Dict, Generator, List, Set +from typing import Any, Dict, Generator, List, Set, cast import pytest from greenlet import greenlet @@ -36,6 +36,7 @@ Error, Page, Playwright, + Route, TimeoutError, sync_playwright, ) @@ -385,3 +386,61 @@ def handler(message: ConsoleMessage) -> None: def test_click_should_accept_timedelta_for_timeout(page: Page) -> None: with pytest.raises(TimeoutError, match="Timeout 1ms exceeded"): page.click("does-not-exist", timeout=timedelta(milliseconds=1)) + + +def test_handlers_should_preserve_base_exception( + context: BrowserContext, server: Server +) -> None: + # Regression test for https://github.com/microsoft/playwright-python/issues/3360. + page = context.new_page() + + def fail_console(msg: ConsoleMessage) -> None: + pytest.fail(f"console: {msg.text}") + + try: + page.on("console", fail_console) + page.evaluate("console.log('hi')") + with pytest.raises(pytest.fail.Exception, match="console: hi"): + page.evaluate("1 + 1") + assert page.evaluate("1 + 1") == 2 + + page.remove_listener("console", fail_console) + seen: List[BaseException] = [] + + def fail_handled(msg: ConsoleMessage) -> None: + pytest.fail(f"handled: {msg.text}") + + cast(Any, page).on("error", seen.append) + page.on("console", fail_handled) + page.evaluate("console.log('ok')") + assert len(seen) == 1 + assert isinstance(seen[0], pytest.fail.Exception) + assert "handled: ok" in str(seen[0]) + assert page.evaluate("1 + 1") == 2 + + page.remove_listener("console", fail_handled) + cast(Any, page).remove_listener("error", seen.append) + + def fail_after_fulfill(route: Route) -> None: + route.fulfill(body="ok") + pytest.fail("route failed") + + page.route("**/empty.html", fail_after_fulfill) + page.goto(server.EMPTY_PAGE) + with pytest.raises(pytest.fail.Exception, match="route failed"): + page.evaluate("1 + 1") + page.unroute("**/empty.html") + + with pytest.raises(pytest.fail.Exception, match="predicate: boom"): + with page.expect_console_message( + lambda msg: pytest.fail(f"predicate: {msg.text}") + ): + page.evaluate("console.log('boom')") + assert page.evaluate("1 + 1") == 2 + + page.expose_function("pwFail", lambda: pytest.fail("binding failed")) + with pytest.raises(Error, match="binding failed"): + page.evaluate("window.pwFail()") + assert page.evaluate("1 + 1") == 2 + finally: + page.close()