Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion playwright/_impl/_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
6 changes: 4 additions & 2 deletions playwright/_impl/event_emitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand All @@ -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)

Expand Down
5 changes: 3 additions & 2 deletions playwright/_impl/out_of_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
29 changes: 29 additions & 0 deletions tests/sync/python/test_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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):
Expand Down
Loading