[Regression]: pytest.fail() inside an event handler closes the connection

Open Beginner friendly
#3,360 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
65/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
python
Domain
backend

Research direction

Run the reproduction script from the report against a local checkout to confirm the current failure, then look at where the sync API dispatches listener callbacks and where a listener's exception is caught. The report narrows it to that catch clause: it handles Exception, and it needs to cover BaseException subclasses such as the ones pytest.fail(), pytest.skip() and pytest.xfail() raise, while still not killing the connection. Done means the run prints 1 Failed console: hi, the error listener still fires, and the page stays usable afterwards; add a regression test next to the existing listener-error tests.

Written by the indexing model from the issue text.

Description

Last Good Version

1.64.0

First Bad Version

1.65.0

Steps to reproduce
import pytest
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    page = p.chromium.launch().new_page()
    page.on("error", lambda e: print("error listener:", e))
    page.on("console", lambda msg: pytest.fail(f"console: {msg.text}"))
    for i in range(2):
        try:
            page.evaluate("console.log('hi')")
            print(i, "ok")
        except BaseException as e:
            print(i, type(e).__name__, str(e).splitlines()[0])
Expected behavior

Same as 1.64:

0 ok
1 Failed console: hi
Actual behavior
0 TargetClosedError Page.evaluate: Target page, context or browser has been closed
1 TargetClosedError Playwright connection closed

The Failed is gone and the connection is dead. The error listener is not called either.

With a plain Exception (e.g. assert False) it still works, so it's only BaseException subclasses — which is what pytest.fail(), pytest.skip() and pytest.xfail() raise. The listener error handling in the dispatch path now catches Exception; before the port it was BaseException.

Additional context

No response

Environment
- Operating System: macOS 27.2
- CPU: arm64
- Browser: Chromium
- Python Version: 3.14
- Other info: sync API
Dominant language
Python
Stars
15.1k
Forks
1.3k
Avg merge
6h 16m
Merged PRs (30d)
53

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from microsoft/playwright-python

All issues in microsoft/playwright-python

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.