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 f09b69275..2b16c3fba 100644 --- a/playwright/_impl/event_emitter.py +++ b/playwright/_impl/event_emitter.py @@ -27,6 +27,7 @@ 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 completed @@ -88,7 +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) - except Exception 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) @@ -109,7 +111,7 @@ def on_done(f: "asyncio.Future[Any]") -> None: else: try: self._handle_listener_error(type, e) - except Exception 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 212f878a5..5dc6bd194 100644 --- a/playwright/_impl/out_of_process.py +++ b/playwright/_impl/out_of_process.py @@ -23,6 +23,7 @@ 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 @@ -47,10 +48,10 @@ 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. try: connection.dispatch(message) - except Exception as error: + except listener_error_types() as error: connection._on_event_listener_error(error) transport.on_message = on_message diff --git a/tests/sync/python/test_sync.py b/tests/sync/python/test_sync.py index c6bec2941..f2e57e898 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,34 @@ 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 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):