tests: the census counts its own server, and a module that leaves a browser open fails (#493)

* tests: the census of a closed context counts only its own server's objects

* tests: a module that leaves a browser open fails, and the unit tests that leaked close theirs

A BrowserDispatcher starts the thread "invpw-thread-starter" and stops it only when its connection's close listeners fire. A unit test that
builds one on a fake connection and never closes it left the thread alive, and with it the connection, the browser and every context for the
rest of the worker (23 files, 635 threads in one of them).

- tests/_browser_census.py, registered in conftest.py: a module-scoped autouse check. When the last test of a module has torn down, the live
  starters must be back to what they were before it (a short join: stop is asynchronous), else the module errors with "left N browser(s)
  open: close their connection". Module level, so a module-scoped browser is fine.
- tests/test_a_module_that_leaves_a_browser_open_fails.py: red on a module that leaks, green on one that closes and on one that shares a
  browser through a module fixture.
- the fake connections of the leaking files register themselves with closes_with_the_test(self) in their __init__; an autouse fixture ends
  them when the test ends with announce_closed(), the real path: it fires the close listeners the dispatcher registered. Nothing intercepts
  the starter, so a test that builds a browser on a connection it did not register still leaves the thread and the module check says so.
This commit is contained in:
Federico Elia authored and GitHub committed 2026-11-14 14:25:14 +01:00
1 parent 45c7450b3e
commit 9d217c4911
17 files changed
+223 -13

No files matched your search

+69
View File
@@ -0,0 +1,69 @@
"""The check that no test module leaves a browser open.
A `BrowserDispatcher` starts one daemon thread, "invpw-thread-starter", and stops it only when the connection's close listeners fire. A
unit test that builds a dispatcher on a fake connection and never closes it leaves that thread alive, and the thread keeps the connection,
the browser and every context alive for the rest of the worker (a gc census of a closed context once found 7 of them, and one file alone
left 635). So the number of live starters, counted when the last test of a module has torn down, must be what it was before the module.
Module level and not per test: a module-scoped browser (the e2e ones) is legitimately open between its tests and closed at the end.
"""
import threading
import time
import pytest
STARTER_NAME = "invpw-thread-starter"
# `stop` is asynchronous: it queues a None and the thread leaves on its next turn. A moment, not a wait for a leak that will not leave.
_JOIN_SECONDS = 5.0
def starters_alive():
return [t for t in threading.enumerate() if t.name == STARTER_NAME and t.is_alive()]
def wait_until_back_to(before, seconds=_JOIN_SECONDS):
"""The starters still alive after `seconds` beyond the `before` that were there already (0 when the module closed everything)."""
deadline = time.monotonic() + seconds
while True:
extra = len(starters_alive()) - before
if extra <= 0 or time.monotonic() >= deadline:
return max(extra, 0)
for t in starters_alive():
t.join(0.05)
@pytest.fixture(scope="module", autouse=True)
def _a_module_leaves_no_browser_open(request):
before = len(starters_alive())
yield
left = wait_until_back_to(before)
if left:
pytest.fail(
"%s left %d browser(s) open: close their connection (fire its close listeners) or shut the server down, in a "
"finally or a fixture teardown. Each one keeps a thread named %r alive, and with it the connection, the browser "
"and every context, for the rest of the worker." % (request.module.__name__, left, STARTER_NAME),
pytrace=False,
)
_made = []
def closes_with_the_test(connection):
"""Register a fake connection a test builds: when the test ends it is closed the way a real one ends, `announce_closed()`, which fires
its close listeners (a `BrowserDispatcher` registered `_starter.stop` on them). Returns the connection, so it goes inline:
`conn = closes_with_the_test(Engine())`, or from the `__init__` of a fake class so that every instance is covered.
Nothing intercepts the starter: a test that builds a browser on a connection it did not register still leaves the thread open, and the
module check above says so.
"""
_made.append(connection)
return connection
@pytest.fixture(autouse=True)
def _the_connections_a_test_made_are_closed_with_it():
yield
made, _made[:] = list(_made), []
for connection in reversed(made):
connection.announce_closed()
+1
View File
@@ -11,6 +11,7 @@ from pathlib import Path
import pytest
from _servers import LocalServer
from _browser_census import _a_module_leaves_no_browser_open, _the_connections_a_test_made_are_closed_with_it # noqa: F401 (autouse)
# ── The watchdog that says WHERE it is stuck, while it is still stuck ─────────
#
@@ -34,6 +34,7 @@ from invisible_playwright._juggler.server import (
ArtifactDispatcher, BrowserContextDispatcher, BrowserDispatcher,
DebuggerDispatcher, JugglerServer, LocalUtilsDispatcher, PageDispatcher,
StreamDispatcher, TracingDispatcher)
from _browser_census import closes_with_the_test
pytestmark = pytest.mark.unit
@@ -44,6 +45,7 @@ class ScriptedJuggler(EventListeners):
def __init__(self):
super().__init__()
closes_with_the_test(self)
self._contexts = itertools.count(1)
self._targets = itertools.count(1)
self.sessions = {}
@@ -150,24 +152,47 @@ def test_the_browser_does_not_keep_the_contexts_it_closed(browser):
assert browser._buffered == {} and browser._live == set()
def _census(browser):
"""What this browser's server built and is still alive, after a collection.
Only ITS objects: another browser of the same process (an earlier test of the
same worker that left its contexts open) is not this server's census."""
kinds = (BrowserContextDispatcher, PageDispatcher, DebuggerDispatcher,
TracingDispatcher)
gc.collect()
return collections.Counter(type(o).__name__ for o in gc.get_objects()
if type(o) in kinds and o.server is browser.server)
def _assert_the_census_is_stable(browser):
for n in range(20):
_cycle(browser, n, close_page_first=n % 2 == 0)
first = _census(browser)
for n in range(20, 60):
_cycle(browser, n, close_page_first=n % 2 == 0)
assert _census(browser) == first
assert first.get("BrowserContextDispatcher", 0) == 0, first
def test_the_count_of_objects_is_stable_across_cycles(browser):
"""The census of what the server builds, after a collection, does not move
between 20 cycles and 60."""
kinds = (BrowserContextDispatcher, PageDispatcher, DebuggerDispatcher,
TracingDispatcher)
_assert_the_census_is_stable(browser)
def census():
gc.collect()
return collections.Counter(type(o).__name__ for o in gc.get_objects()
if type(o) in kinds)
for n in range(20):
_cycle(browser, n, close_page_first=n % 2 == 0)
first = census()
for n in range(20, 60):
_cycle(browser, n, close_page_first=n % 2 == 0)
assert census() == first
assert first.get("BrowserContextDispatcher", 0) == 0, first
def test_the_census_does_not_count_another_browsers_open_context(browser):
# The census counted every dispatcher of the process: run after a file that
# leaves its contexts open in the same worker, it saw 7 BrowserContextDispatcher
# that were not this server's (core #272, wrapper-on-this-core linux part 2).
server = remote._SharedServer()
other = remote.SharedBrowserDispatcher(server, remote.SharedBrowserType(server),
ScriptedJuggler(), "firefox/1")
left_open = server.object(server.handle(
{"guid": other.guid, "method": "newContext", "params": {}})["context"]["guid"])
try:
_assert_the_census_is_stable(browser)
assert left_open.guid in server._objects
finally:
server.shutdown()
def test_a_download_and_its_stream_are_let_go_with_their_context(browser):
@@ -29,6 +29,7 @@ from invisible_core.juggler.connection import EventListeners
from invisible_playwright import _session
from invisible_playwright._juggler.server import (BrowserDispatcher, Server, UDP_STUN_PREF,
session_udp_stun_servers, take_session_motion)
from _browser_census import closes_with_the_test
pytestmark = pytest.mark.unit
@@ -39,6 +40,7 @@ STUN = ["%s:%d" % (STUN_NUMBER, STUN_PORT)]
class _Connection(EventListeners):
def __init__(self, gateways=()):
super().__init__()
closes_with_the_test(self)
self.sent = []
self.datagrams_before = {}
self._gateways = gateways
@@ -16,6 +16,7 @@ from invisible_core.juggler.connection import EventListeners
from invisible_playwright._juggler.server import (
BrowserContextDispatcher, BrowserDispatcher, Server,
)
from _browser_census import closes_with_the_test
class _Engine(EventListeners):
@@ -23,6 +24,7 @@ class _Engine(EventListeners):
def __init__(self):
super().__init__()
closes_with_the_test(self)
self.sent = []
def startup_send(self, method, params=None):
+2
View File
@@ -24,6 +24,7 @@ from invisible_playwright._juggler.server import (
BrowserTypeDispatcher, JugglerServer)
from invisible_playwright._juggler.transport import _translate_exception
from invisible_playwright.sync_api import TimeoutError as PlaywrightTimeout
from _browser_census import closes_with_the_test
PROXY = {"server": "socks5://127.0.0.1:1080", "username": "u", "password": "p"}
@@ -34,6 +35,7 @@ class _Engine(EventListeners):
def __init__(self, silent=()):
EventListeners.__init__(self)
closes_with_the_test(self)
self.silent = set(silent)
self.bounds: dict = {}
self.startup: list = []
@@ -24,6 +24,7 @@ from invisible_playwright import _session
from invisible_playwright._juggler import server as module
from invisible_playwright._juggler.server import (SESSION_SEED_PREF, BrowserTypeDispatcher,
JugglerServer)
from _browser_census import closes_with_the_test
# Read with a default so that, on the code before the fix, the test fails on what the
# profile holds and not on an import.
@@ -35,6 +36,7 @@ _LINE = re.compile(r'^user_pref\("([^"]+)",\s*(.*)\);\s*$')
class _Engine(EventListeners):
def __init__(self):
EventListeners.__init__(self)
closes_with_the_test(self)
def send(self, method, params=None, session=None, timeout=30.0):
return {"browserContextId": "ctx-1", "targetId": "t-1"}
@@ -0,0 +1,83 @@
"""The check of tests/_browser_census.py is red on a module that leaks a browser and green on one that closes it.
Each case is a module of its own in a fresh pytest (the check is module level and the leak would otherwise count against this file).
"""
import os
import subprocess
import sys
import textwrap
from pathlib import Path
TESTS = str(Path(__file__).resolve().parent)
_BUILD = """
from invisible_playwright._juggler.server import _ThreadStarter
def build():
return _ThreadStarter(on_error=lambda message: None)
"""
def _run(tmp_path, body):
(tmp_path / "conftest.py").write_text("from _browser_census import _a_module_leaves_no_browser_open # noqa\n")
(tmp_path / "test_the_module.py").write_text(textwrap.dedent(_BUILD) + textwrap.dedent(body))
env = dict(os.environ, PYTHONPATH=TESTS + os.pathsep + os.environ.get("PYTHONPATH", ""))
return subprocess.run(
[sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "-o", "addopts=", str(tmp_path / "test_the_module.py")],
cwd=str(tmp_path), env=env, capture_output=True, text=True, timeout=120,
)
def test_a_module_that_never_closes_what_it_built_fails(tmp_path):
done = _run(tmp_path, """
def test_one():
build()
def test_two():
build()
""")
out = done.stdout + done.stderr
assert done.returncode != 0, out
assert "left 2 browser(s) open: close their connection" in out, out
assert "2 passed" in out and "1 error" in out, out # the tests pass; the module is the one that fails
def test_a_module_that_closes_what_it_built_passes(tmp_path):
done = _run(tmp_path, """
import pytest
@pytest.fixture
def starter():
built = build()
yield built
built.stop()
def test_one(starter):
pass
def test_two(starter):
pass
""")
out = done.stdout + done.stderr
assert done.returncode == 0, out
assert "2 passed" in out and "error" not in out, out
def test_a_browser_shared_by_the_tests_of_a_module_may_stay_open_until_the_module_ends(tmp_path):
done = _run(tmp_path, """
import pytest
@pytest.fixture(scope="module")
def shared():
built = build()
yield built
built.stop()
def test_one(shared):
pass
def test_two(shared):
pass
""")
out = done.stdout + done.stderr
assert done.returncode == 0, out
assert "2 passed" in out, out
@@ -19,6 +19,7 @@ from invisible_playwright._juggler import server as srv
from invisible_playwright._juggler.server import (
BrowserContextDispatcher, BrowserDispatcher, Server,
)
from _browser_census import closes_with_the_test
#: How long this engine takes to answer `Browser.newPage`, in its own clock.
ANSWER_AFTER_S = 35.0
@@ -30,6 +31,7 @@ class _SlowEngine(EventListeners):
def __init__(self):
super().__init__()
closes_with_the_test(self)
self.browser = None
self.bounds = []
+2
View File
@@ -22,6 +22,7 @@ import pytest
from invisible_core import SessionGeo, SessionLocale, decide_session_locale
from invisible_core.juggler.connection import EventListeners
from invisible_playwright._juggler.server import BrowserDispatcher, Server
from _browser_census import closes_with_the_test
_PKG_DIR = pathlib.Path(__file__).resolve().parent.parent / "src" / "invisible_playwright"
@@ -29,6 +30,7 @@ _PKG_DIR = pathlib.Path(__file__).resolve().parent.parent / "src" / "invisible_p
class _Connection(EventListeners):
def __init__(self):
super().__init__()
closes_with_the_test(self)
self.sent = []
def startup_send(self, method, params=None):
@@ -36,11 +36,16 @@ from invisible_core.juggler.connection import EventListeners
from invisible_playwright._juggler.server import BrowserDispatcher, Server
from _servers import LocalServer
from _browser_census import closes_with_the_test
SEED = 106
class _Connection(EventListeners):
def __init__(self):
super().__init__()
closes_with_the_test(self)
def startup_send(self, method, params=None):
return self.send(method, params, timeout=None)
+2
View File
@@ -22,6 +22,7 @@ import pytest
from invisible_playwright._juggler.server import BrowserDispatcher, Server
from invisible_core.juggler.connection import EventListeners
from _browser_census import closes_with_the_test
class FakeConnection(EventListeners):
@@ -29,6 +30,7 @@ class FakeConnection(EventListeners):
def __init__(self):
super().__init__()
closes_with_the_test(self)
self.sent = []
def startup_send(self, method, params=None):
+5
View File
@@ -20,6 +20,7 @@ from invisible_playwright._juggler import transport as factory
from invisible_core.juggler.connection import EventListeners, ProtocolError
from _servers import LocalServer
from _browser_census import closes_with_the_test
PAGE = b"""<!doctype html><html><head><title>seam</title></head><body>
<button id=b onclick="this.dataset.n=(+(this.dataset.n||0)+1)">press</button>
@@ -902,6 +903,7 @@ def test_a_profile_WE_made_is_removed_and_the_caller_s_is_not():
def __init__(self):
EventListeners.__init__(self)
closes_with_the_test(self)
def startup_send(self, method, params=None):
return self.send(method, params, timeout=None)
@@ -967,6 +969,7 @@ def test_the_profile_is_removed_after_the_browser_has_closed(monkeypatch):
class FakeConnection(EventListeners):
def __init__(self, profile_dir, refuse_proxy=False):
EventListeners.__init__(self)
closes_with_the_test(self)
self._profile = pathlib.Path(profile_dir)
self._refuse_proxy = refuse_proxy
@@ -1066,6 +1069,7 @@ def test_the_launch_handler_hands_the_named_environment_to_the_engine(monkeypatc
class FakeConnection(EventListeners):
def __init__(self):
EventListeners.__init__(self)
closes_with_the_test(self)
def startup_send(self, method, params=None):
return self.send(method, params, timeout=None)
@@ -1124,6 +1128,7 @@ def test_the_browser_s_temporary_files_live_and_end_with_the_session(monkeypatch
class FakeConnection(EventListeners):
def __init__(self, tmp):
EventListeners.__init__(self)
closes_with_the_test(self)
self._tmp = tmp
def startup_send(self, method, params=None):
@@ -20,11 +20,13 @@ import pytest
from invisible_core.juggler.connection import EventListeners
from invisible_playwright._juggler.server import (BrowserDispatcher,
PageDispatcher, Server)
from _browser_census import closes_with_the_test
class _Connection(EventListeners):
def __init__(self):
super().__init__()
closes_with_the_test(self)
self.sent = []
def startup_send(self, method, params=None):
@@ -43,6 +43,7 @@ from invisible_playwright._pw._impl._browser import Browser
from invisible_playwright._pw._impl._browser_context import (
BrowserContext, page_number_for_call,
)
from _browser_census import closes_with_the_test
# -- the client: the number is reserved at the call --------------------------
@@ -196,6 +197,7 @@ class _Engine(EventListeners):
def __init__(self):
super().__init__()
closes_with_the_test(self)
self.browser = None
self.arrived = threading.Semaphore(0)
self.release = [threading.Event() for _ in range(8)]
+2
View File
@@ -10,6 +10,7 @@ from invisible_playwright._juggler.server import (
BrowserTypeDispatcher,
JugglerServer,
)
from _browser_census import closes_with_the_test
pytestmark = pytest.mark.unit
_COMMAND = "Browser.setServiceWorkersBlocked"
@@ -18,6 +19,7 @@ _COMMAND = "Browser.setServiceWorkersBlocked"
class _Connection(EventListeners):
def __init__(self, failure=None):
super().__init__()
closes_with_the_test(self)
self.sent = []
#: Download options are sent for every context; kept apart so the
#: ordering assertions below stay about the worker policy.
@@ -22,6 +22,7 @@ from invisible_playwright import InvisiblePlaywright, _session
from invisible_playwright._juggler import remote
from invisible_playwright._juggler.server import BrowserDispatcher, Server
from invisible_playwright.async_api import InvisiblePlaywright as AsyncInvisiblePlaywright
from _browser_census import closes_with_the_test
_PKG = pathlib.Path(__file__).resolve().parent.parent / "src" / "invisible_playwright"
EXIT = (45.0, 9.0)
@@ -45,6 +46,7 @@ def _past_geo(cls, seed=42, geo=None):
class _Connection(EventListeners):
def __init__(self):
super().__init__()
closes_with_the_test(self)
self.sent = []
def startup_send(self, method, params=None):