Skip to content

Commit 6baffde

Browse files
fix: resolve test hang with websockets 14+
The test suite hangs after upgrading websockets from 13.x to 14.x/15.x because websockets 14.0 switched to a new asyncio implementation by default. Changes: 1. In TestServer.serve(): Replace deprecated asyncio.get_event_loop() pattern with asyncio.create_task() which is the modern way to create tasks when already inside an async context. 2. In serve_in_thread(): Instead of relying on server.run() which uses asyncio.run(), explicitly create a new event loop in the background thread with asyncio.new_event_loop() and asyncio.set_event_loop(). 3. Remove loop="asyncio" from Config() since we now manage the event loop manually. This approach is compatible with uvicorn 0.36+ (which removed the deprecated setup_event_loop() method) and works with websockets 14+. Fixes #3708
1 parent def4778 commit 6baffde

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

tests/conftest.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -235,10 +235,9 @@ def install_signal_handlers(self) -> None:
235235
async def serve(self, sockets=None):
236236
self.restart_requested = asyncio.Event()
237237

238-
loop = asyncio.get_event_loop()
239238
tasks = {
240-
loop.create_task(super().serve(sockets=sockets)),
241-
loop.create_task(self.watch_restarts()),
239+
asyncio.create_task(super().serve(sockets=sockets)),
240+
asyncio.create_task(self.watch_restarts()),
242241
}
243242
await asyncio.wait(tasks)
244243

@@ -269,7 +268,15 @@ async def watch_restarts(self) -> None: # pragma: no cover
269268

270269

271270
def serve_in_thread(server: TestServer) -> typing.Iterator[TestServer]:
272-
thread = threading.Thread(target=server.run)
271+
def run_server():
272+
loop = asyncio.new_event_loop()
273+
asyncio.set_event_loop(loop)
274+
try:
275+
loop.run_until_complete(server.serve())
276+
finally:
277+
loop.close()
278+
279+
thread = threading.Thread(target=run_server)
273280
thread.start()
274281
try:
275282
while not server.started:
@@ -282,6 +289,6 @@ def serve_in_thread(server: TestServer) -> typing.Iterator[TestServer]:
282289

283290
@pytest.fixture(scope="session")
284291
def server() -> typing.Iterator[TestServer]:
285-
config = Config(app=app, lifespan="off", loop="asyncio")
292+
config = Config(app=app, lifespan="off")
286293
server = TestServer(config=config)
287294
yield from serve_in_thread(server)

0 commit comments

Comments
 (0)