| 1 | """Retry helpers for libtmux and downstream libtmux libraries.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import time |
| 6 | import typing as t |
| 7 | |
| 8 | from libtmux.exc import WaitTimeout |
| 9 | from libtmux.test.constants import ( |
| 10 | RETRY_INTERVAL_SECONDS, |
| 11 | RETRY_TIMEOUT_SECONDS, |
| 12 | ) |
| 13 | |
| 14 | if t.TYPE_CHECKING: |
| 15 | import sys |
| 16 | from collections.abc import Callable |
| 17 | |
| 18 | if sys.version_info >= (3, 11): |
| 19 | pass |
| 20 | |
| 21 | |
| 22 | def retry_until( |
| 23 | fun: Callable[[], bool], |
| 24 | seconds: float = RETRY_TIMEOUT_SECONDS, |
| 25 | *, |
| 26 | interval: float = RETRY_INTERVAL_SECONDS, |
| 27 | raises: bool | None = True, |
| 28 | ) -> bool: |
| 29 | """ |
| 30 | Retry a function until a condition meets or the specified time passes. |
| 31 | |
| 32 | Parameters |
| 33 | ---------- |
| 34 | fun : callable |
| 35 | A function that will be called repeatedly until it returns ``True`` or |
| 36 | the specified time passes. |
| 37 | seconds : float |
| 38 | Seconds to retry. Defaults to ``8``, which is configurable via |
| 39 | ``RETRY_TIMEOUT_SECONDS`` environment variables. |
| 40 | interval : float |
| 41 | Time in seconds to wait between calls. Defaults to ``0.05`` and is |
| 42 | configurable via ``RETRY_INTERVAL_SECONDS`` environment variable. |
| 43 | raises : bool |
| 44 | Whether or not to raise an exception on timeout. Defaults to ``True``. |
| 45 | |
| 46 | Examples |
| 47 | -------- |
| 48 | >>> def fn(): |
| 49 | ... p = session.active_window.active_pane |
| 50 | ... return p.pane_current_path is not None |
| 51 | |
| 52 | >>> retry_until(fn) |
| 53 | True |
| 54 | |
| 55 | In pytest: |
| 56 | |
| 57 | >>> assert retry_until(fn, raises=False) |
| 58 | """ |
| 59 | ini = time.time() |
| 60 | |
| 61 | while not fun(): |
| 62 | end = time.time() |
| 63 | if end - ini >= seconds: |
| 64 | if raises: |
| 65 | raise WaitTimeout |
| 66 | return False |
| 67 | time.sleep(interval) |
| 68 | return True |