test_find_agent_rate_limit.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. """跨线程异步限速单元测试。"""
  2. from __future__ import annotations
  3. import asyncio
  4. import threading
  5. import time
  6. from agents.find_agent.support.rate_limit import make_async_interval_limiter
  7. def test_async_interval_limiter_is_safe_across_threads() -> None:
  8. wait = make_async_interval_limiter(0.05)
  9. hits: list[float] = []
  10. lock = threading.Lock()
  11. errors: list[BaseException] = []
  12. def worker() -> None:
  13. loop = asyncio.new_event_loop()
  14. asyncio.set_event_loop(loop)
  15. try:
  16. for _ in range(2):
  17. loop.run_until_complete(wait())
  18. with lock:
  19. hits.append(time.monotonic())
  20. except BaseException as exc: # noqa: BLE001 - collect for assertion
  21. with lock:
  22. errors.append(exc)
  23. finally:
  24. loop.close()
  25. asyncio.set_event_loop(None)
  26. threads = [threading.Thread(target=worker) for _ in range(3)]
  27. for thread in threads:
  28. thread.start()
  29. for thread in threads:
  30. thread.join(timeout=5)
  31. assert not thread.is_alive()
  32. assert not errors
  33. assert len(hits) == 6
  34. ordered = sorted(hits)
  35. for prev, curr in zip(ordered, ordered[1:]):
  36. assert curr - prev >= 0.04