diff --git a/playwright/_impl/waiter.py b/playwright/_impl/waiter.py index 0878dfe79..795f794a5 100644 --- a/playwright/_impl/waiter.py +++ b/playwright/_impl/waiter.py @@ -240,7 +240,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,6 +256,11 @@ def run() -> Any: async def continuation() -> None: try: settle(bool(await matched)) + except asyncio.CancelledError as e: + # Python: settle the wait and remove its listener before + # propagating cancellation of the predicate task. + fail(e) + raise except Exception as e: fail(e) diff --git a/tests/async/python/test_page.py b/tests/async/python/test_page.py index a942df552..63cc37278 100644 --- a/tests/async/python/test_page.py +++ b/tests/async/python/test_page.py @@ -14,7 +14,9 @@ """Python only: tests of behaviors that no upstream test covers.""" -from typing import Any, AsyncGenerator, Dict +import asyncio +import sys +from typing import Any, AsyncGenerator, Dict, Type import pytest @@ -46,18 +48,35 @@ async def test_wait_for_request_should_work_with_predicate( assert request.url == server.PREFIX + "/digits/2.png" +@pytest.mark.parametrize( + "error_type", + [ + Exception, + pytest.param( + asyncio.CancelledError, + marks=pytest.mark.skipif( + sys.version_info < (3, 11), + reason="Python 3.10 does not preserve the CancelledError message", + ), + ), + ], +) async def test_expect_response_should_reject_when_async_predicate_throws( - page: Page, server: Server + page: Page, server: Server, error_type: Type[BaseException] ) -> None: + # Regression test for https://github.com/microsoft/playwright-python/issues/3379. await page.goto(server.EMPTY_PAGE) + listener_count = page._impl_obj.listener_count("response") async def predicate(response: Any) -> bool: - raise Exception("Async oops!") + raise error_type("Async oops!") - with pytest.raises(Exception, match="Async oops!"): - async with page.expect_response(predicate): + with pytest.raises(error_type, match="Async oops!"): + async with page.expect_response(predicate, timeout=1_000): await page.evaluate("() => fetch('/digits/1.png')") + assert page._impl_obj.listener_count("response") == listener_count + async def test_expect_response_should_reject_when_sync_predicate_throws( page: Page, server: Server