test: synchronize watchdog log rotation assertions

This commit is contained in:
RuochenPan
2026-09-09 09:39:59 +08:00
parent 20ad3dcde2
commit 7de4e55c0e
+15 -7
View File
@@ -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