feat: 添加 _wait_for 辅助函数以优化测试中的等待逻辑,调整 FileWatcher 的防抖设置

This commit is contained in:
DrSmoothl
2026-03-09 14:35:54 +08:00
parent fbf946b352
commit 5b7945ac7b

View File

@@ -107,13 +107,23 @@ async def test_unsubscribe_stops_dispatch(tmp_path: Path):
assert calls == 0 assert calls == 0
async def _wait_for(predicate, timeout: float = 5.0, interval: float = 0.05):
"""轮询等待 predicate() 为真,避免依赖固定 sleep 导致跨平台不稳定。"""
deadline = asyncio.get_event_loop().time() + timeout
while asyncio.get_event_loop().time() < deadline:
if predicate():
return
await asyncio.sleep(interval)
raise TimeoutError(f"等待超时({timeout}s)")
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_add_callback_while_watcher_running(tmp_path: Path): async def test_add_callback_while_watcher_running(tmp_path: Path):
dirs = (tmp_path / "a_dir").resolve() dirs = (tmp_path / "a_dir").resolve()
dirs.mkdir(exist_ok=True) dirs.mkdir(exist_ok=True)
file = (dirs / "a.toml").resolve() file = (dirs / "a.toml").resolve()
file.touch() file.touch()
watcher = FileWatcher(paths=[dirs]) watcher = FileWatcher(paths=[dirs], debounce_ms=200)
calls = 0 calls = 0
@@ -124,15 +134,15 @@ async def test_add_callback_while_watcher_running(tmp_path: Path):
uuid = watcher.subscribe(callback, paths=[file]) uuid = watcher.subscribe(callback, paths=[file])
await watcher.start() await watcher.start()
with file.open("w") as f: try:
f.write("change") with file.open("w") as f:
await asyncio.sleep(0.5) f.write("change")
with file.open("r") as f: await _wait_for(lambda: calls >= 1)
content = f.read() assert calls == 1
print(content) watcher.unsubscribe(uuid)
assert calls == 1 with file.open("w") as f:
watcher.unsubscribe(uuid) f.write("change2")
with file.open("w") as f: await asyncio.sleep(1.0)
f.write("change2") assert calls == 1
await asyncio.sleep(0.5) finally:
assert calls == 1 await watcher.stop()