From 7de4e55c0e739645241d26a7fe406069e2a4cc54 Mon Sep 17 00:00:00 2001 From: RuochenPan Date: Wed, 9 Sep 2026 09:39:59 +0800 Subject: [PATCH] test: synchronize watchdog log rotation assertions --- tests/unit/test_event_loop_diagnostics.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/tests/unit/test_event_loop_diagnostics.py b/tests/unit/test_event_loop_diagnostics.py index 0e1b7c2bd..e2c462153 100644 --- a/tests/unit/test_event_loop_diagnostics.py +++ b/tests/unit/test_event_loop_diagnostics.py @@ -1,6 +1,5 @@ import asyncio import threading -import time import pytest @@ -52,11 +51,18 @@ async def test_event_loop_watchdog_stops_worker_thread(): @pytest.mark.asyncio -async def test_event_loop_watchdog_writes_rotating_log(tmp_path): +async def test_event_loop_watchdog_writes_rotating_log(tmp_path, monkeypatch): """The watchdog should write to and rotate its log file.""" log_path = tmp_path / "logs" / "event_loop_watchdog.log" log_path.parent.mkdir() log_path.write_text("x" * 8, encoding="utf-8") + stack_written = threading.Event() + print_stack = diagnostics.traceback.print_stack + monkeypatch.setattr( + diagnostics.traceback, + "print_stack", + lambda *args, **kwargs: (print_stack(*args, **kwargs), stack_written.set()), + ) task = asyncio.create_task( diagnostics.event_loop_watchdog( @@ -66,11 +72,13 @@ async def test_event_loop_watchdog_writes_rotating_log(tmp_path): max_bytes=4, ) ) - await asyncio.sleep(0) - time.sleep(0.05) # noqa: ASYNC251 - Intentionally block the event loop. - await asyncio.sleep(0.02) - task.cancel() - await asyncio.gather(task, return_exceptions=True) + try: + await asyncio.sleep(0) + # Keep the test frame on the stack until the watchdog writes it. + assert stack_written.wait(timeout=2) + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) log_content = log_path.read_text(encoding="utf-8") assert "Event loop stalled for" in log_content