diff --git a/pytest-playwright-asyncio/pytest_playwright_asyncio/pytest_playwright.py b/pytest-playwright-asyncio/pytest_playwright_asyncio/pytest_playwright.py index ccc1432..694bda9 100644 --- a/pytest-playwright-asyncio/pytest_playwright_asyncio/pytest_playwright.py +++ b/pytest-playwright-asyncio/pytest_playwright_asyncio/pytest_playwright.py @@ -617,8 +617,10 @@ async def _new_context(**kwargs: Any) -> BrowserContext: original_close = context.close async def _close_wrapper(*args: Any, **kwargs: Any) -> None: - contexts.remove(context) - await _artifacts_recorder.on_will_close_browser_context(context) + # BrowserContext.close() may be called more than once. + if context in contexts: + contexts.remove(context) + await _artifacts_recorder.on_will_close_browser_context(context) await original_close(*args, **kwargs) context.close = _close_wrapper diff --git a/pytest-playwright/pytest_playwright/pytest_playwright.py b/pytest-playwright/pytest_playwright/pytest_playwright.py index 4a6a5a2..93fad36 100644 --- a/pytest-playwright/pytest_playwright/pytest_playwright.py +++ b/pytest-playwright/pytest_playwright/pytest_playwright.py @@ -612,8 +612,10 @@ def _new_context(**kwargs: Any) -> BrowserContext: original_close = context.close def _close_wrapper(*args: Any, **kwargs: Any) -> None: - contexts.remove(context) - _artifacts_recorder.on_will_close_browser_context(context) + # BrowserContext.close() may be called more than once. + if context in contexts: + contexts.remove(context) + _artifacts_recorder.on_will_close_browser_context(context) original_close(*args, **kwargs) context.close = _close_wrapper diff --git a/tests/test_asyncio.py b/tests/test_asyncio.py index 26e83a0..f9452de 100644 --- a/tests/test_asyncio.py +++ b/tests/test_asyncio.py @@ -1532,6 +1532,31 @@ async def test_artifact_collection(browser, page, new_context): ) +def test_context_can_be_closed_twice(testdir: pytest.Testdir) -> None: + testdir.makepyfile( + """ + import pytest + + @pytest.mark.asyncio + async def test_close_twice(context): + page = await context.new_page() + await page.goto("data:text/html,