Skip to content

Commit 4d31bdc

Browse files
authored
fix(asyncio): already cancelled tasks ends up in 'InvalidStateError: invalid state' (#2593)
1 parent a71a0ce commit 4d31bdc

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

playwright/_impl/_connection.py

+2
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,8 @@ def cleanup(self, cause: str = None) -> None:
294294
# To prevent 'Future exception was never retrieved' we ignore all callbacks that are no_reply.
295295
if callback.no_reply:
296296
continue
297+
if callback.future.cancelled():
298+
continue
297299
callback.future.set_exception(self._closed_error)
298300
self._callbacks.clear()
299301
self.emit("close")

tests/async/test_asyncio.py

+21-1
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,12 @@
1313
# limitations under the License.
1414
import asyncio
1515
import gc
16+
import sys
1617
from typing import Dict
1718

1819
import pytest
1920

20-
from playwright.async_api import async_playwright
21+
from playwright.async_api import Page, async_playwright
2122
from tests.server import Server
2223
from tests.utils import TARGET_CLOSED_ERROR_MESSAGE
2324

@@ -67,3 +68,22 @@ async def test_cancel_pending_protocol_call_on_playwright_stop(server: Server) -
6768
with pytest.raises(Exception) as exc_info:
6869
await pending_task
6970
assert TARGET_CLOSED_ERROR_MESSAGE in str(exc_info.value)
71+
72+
73+
async def test_should_not_throw_with_taskgroup(page: Page) -> None:
74+
if sys.version_info < (3, 11):
75+
pytest.skip("TaskGroup is only available in Python 3.11+")
76+
77+
from builtins import ExceptionGroup # type: ignore
78+
79+
async def raise_exception() -> None:
80+
raise ValueError("Something went wrong")
81+
82+
with pytest.raises(ExceptionGroup) as exc_info:
83+
async with asyncio.TaskGroup() as group: # type: ignore
84+
group.create_task(page.locator(".this-element-does-not-exist").inner_text())
85+
group.create_task(raise_exception())
86+
assert len(exc_info.value.exceptions) == 1
87+
assert "Something went wrong" in str(exc_info.value.exceptions[0])
88+
assert isinstance(exc_info.value.exceptions[0], ValueError)
89+
assert await page.evaluate("() => 11 * 11") == 121

0 commit comments

Comments
 (0)