From 5b7945ac7b2a3a254aa1c63173282f15b429117c Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 9 Mar 2026 14:35:54 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=20=5Fwait=5Ffor=20?= =?UTF-8?q?=E8=BE=85=E5=8A=A9=E5=87=BD=E6=95=B0=E4=BB=A5=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E4=B8=AD=E7=9A=84=E7=AD=89=E5=BE=85=E9=80=BB?= =?UTF-8?q?=E8=BE=91=EF=BC=8C=E8=B0=83=E6=95=B4=20FileWatcher=20=E7=9A=84?= =?UTF-8?q?=E9=98=B2=E6=8A=96=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pytests/config_test/test_file_watcher.py | 36 +++++++++++++++--------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/pytests/config_test/test_file_watcher.py b/pytests/config_test/test_file_watcher.py index c2fdd9b2..a6b86477 100644 --- a/pytests/config_test/test_file_watcher.py +++ b/pytests/config_test/test_file_watcher.py @@ -107,13 +107,23 @@ async def test_unsubscribe_stops_dispatch(tmp_path: Path): 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 async def test_add_callback_while_watcher_running(tmp_path: Path): dirs = (tmp_path / "a_dir").resolve() dirs.mkdir(exist_ok=True) file = (dirs / "a.toml").resolve() file.touch() - watcher = FileWatcher(paths=[dirs]) + watcher = FileWatcher(paths=[dirs], debounce_ms=200) calls = 0 @@ -124,15 +134,15 @@ async def test_add_callback_while_watcher_running(tmp_path: Path): uuid = watcher.subscribe(callback, paths=[file]) await watcher.start() - with file.open("w") as f: - f.write("change") - await asyncio.sleep(0.5) - with file.open("r") as f: - content = f.read() - print(content) - assert calls == 1 - watcher.unsubscribe(uuid) - with file.open("w") as f: - f.write("change2") - await asyncio.sleep(0.5) - assert calls == 1 \ No newline at end of file + try: + with file.open("w") as f: + f.write("change") + await _wait_for(lambda: calls >= 1) + assert calls == 1 + watcher.unsubscribe(uuid) + with file.open("w") as f: + f.write("change2") + await asyncio.sleep(1.0) + assert calls == 1 + finally: + await watcher.stop() \ No newline at end of file