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